From b3f19596d9b7478775ee5ce453ad7bcc32a0152a Mon Sep 17 00:00:00 2001 From: lindsay Date: Mon, 17 Jun 2024 18:33:36 +0200 Subject: [PATCH] Rebuild --- dist/xeokit-sdk.cjs.js | 196 ++++++---- dist/xeokit-sdk.es.js | 196 ++++++---- dist/xeokit-sdk.es5.js | 780 +++++++++++++++++++------------------ dist/xeokit-sdk.min.cjs.js | 4 +- dist/xeokit-sdk.min.es.js | 4 +- dist/xeokit-sdk.min.es5.js | 8 +- 6 files changed, 621 insertions(+), 567 deletions(-) diff --git a/dist/xeokit-sdk.cjs.js b/dist/xeokit-sdk.cjs.js index 5af7316f5..b6f683b6c 100644 --- a/dist/xeokit-sdk.cjs.js +++ b/dist/xeokit-sdk.cjs.js @@ -10763,7 +10763,7 @@ class Marker extends Component { this.scene.camera.off(this._onCameraProjMatrix); if (this._entity) { if (this._onEntityDestroyed !== null) { - this._entity.off(this._onEntityDestroyed); + this._entity.model.off(this._onEntityDestroyed); } if (this._onEntityModelDestroyed !== null) { this._entity.model.off(this._onEntityModelDestroyed); @@ -18735,6 +18735,9 @@ const Renderer$1 = function (scene, options) { let drawableTypeInfo = {}; let drawables = {}; + let postSortDrawableList = []; + let postCullDrawableList = []; + let drawableListDirty = true; let stateSortDirty = true; let imageDirty = true; @@ -18960,28 +18963,38 @@ const Renderer$1 = function (scene, options) { const drawableInfo = drawableTypeInfo[type]; if (drawableInfo.isStateSortable) { drawableInfo.drawableListPreCull.sort(drawableInfo.stateSortCompare); + + drawableInfo.drawableList = drawableInfo.drawableListPreCull; } } } - } - - function cullDrawableList() { + let lenDrawableList = 0; for (let type in drawableTypeInfo) { if (drawableTypeInfo.hasOwnProperty(type)) { const drawableInfo = drawableTypeInfo[type]; const drawableListPreCull = drawableInfo.drawableListPreCull; - const drawableList = drawableInfo.drawableList; - let lenDrawableList = 0; for (let i = 0, len = drawableListPreCull.length; i < len; i++) { const drawable = drawableListPreCull[i]; - drawable.rebuildRenderFlags(); - if (!drawable.renderFlags.culled) { - drawableList[lenDrawableList++] = drawable; - } + postSortDrawableList[lenDrawableList++] = drawable; } - drawableList.length = lenDrawableList; } } + postSortDrawableList.length = lenDrawableList; + postSortDrawableList.sort((a, b) => { + return a.renderOrder - b.renderOrder; + }); + } + + function cullDrawableList() { + let lenDrawableList = 0; + for (let i = 0, len = postSortDrawableList.length; i < len; i++) { + const drawable = postSortDrawableList[i]; + drawable.rebuildRenderFlags(); + if (!drawable.renderFlags.culled) { + postCullDrawableList[lenDrawableList++] = drawable; + } + } + postCullDrawableList.length = lenDrawableList; } function draw(params) { @@ -19214,7 +19227,6 @@ const Renderer$1 = function (scene, options) { } let i; - let len; let drawable; const startTime = Date.now(); @@ -19247,93 +19259,85 @@ const Renderer$1 = function (scene, options) { // Render normal opaque solids, defer others to bins to render after //------------------------------------------------------------------------------------------------------ - for (let type in drawableTypeInfo) { - if (drawableTypeInfo.hasOwnProperty(type)) { - - const drawableInfo = drawableTypeInfo[type]; - const drawableList = drawableInfo.drawableList; - - for (i = 0, len = drawableList.length; i < len; i++) { + for (let i = 0, len = postCullDrawableList.length; i < len; i++) { - drawable = drawableList[i]; + drawable = postCullDrawableList[i]; - if (drawable.culled === true || drawable.visible === false) { - continue; - } + if (drawable.culled === true || drawable.visible === false) { + continue; + } - const renderFlags = drawable.renderFlags; + const renderFlags = drawable.renderFlags; - if (renderFlags.colorOpaque) { - if (saoEnabled && saoPossible && drawable.saoEnabled) { - normalDrawSAOBin[normalDrawSAOBinLen++] = drawable; - } else { - drawable.drawColorOpaque(frameCtx); - } - } + if (renderFlags.colorOpaque) { + if (saoEnabled && saoPossible && drawable.saoEnabled) { + normalDrawSAOBin[normalDrawSAOBinLen++] = drawable; + } else { + drawable.drawColorOpaque(frameCtx); + } + } - if (transparentEnabled) { - if (renderFlags.colorTransparent) { - normalFillTransparentBin[normalFillTransparentBinLen++] = drawable; - } - } + if (transparentEnabled) { + if (renderFlags.colorTransparent) { + normalFillTransparentBin[normalFillTransparentBinLen++] = drawable; + } + } - if (renderFlags.xrayedSilhouetteTransparent) { - xrayedFillTransparentBin[xrayedFillTransparentBinLen++] = drawable; - } + if (renderFlags.xrayedSilhouetteTransparent) { + xrayedFillTransparentBin[xrayedFillTransparentBinLen++] = drawable; + } - if (renderFlags.xrayedSilhouetteOpaque) { - xrayedFillOpaqueBin[xrayedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.xrayedSilhouetteOpaque) { + xrayedFillOpaqueBin[xrayedFillOpaqueBinLen++] = drawable; + } - if (renderFlags.highlightedSilhouetteTransparent) { - highlightedFillTransparentBin[highlightedFillTransparentBinLen++] = drawable; - } + if (renderFlags.highlightedSilhouetteTransparent) { + highlightedFillTransparentBin[highlightedFillTransparentBinLen++] = drawable; + } - if (renderFlags.highlightedSilhouetteOpaque) { - highlightedFillOpaqueBin[highlightedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.highlightedSilhouetteOpaque) { + highlightedFillOpaqueBin[highlightedFillOpaqueBinLen++] = drawable; + } - if (renderFlags.selectedSilhouetteTransparent) { - selectedFillTransparentBin[selectedFillTransparentBinLen++] = drawable; - } + if (renderFlags.selectedSilhouetteTransparent) { + selectedFillTransparentBin[selectedFillTransparentBinLen++] = drawable; + } - if (renderFlags.selectedSilhouetteOpaque) { - selectedFillOpaqueBin[selectedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.selectedSilhouetteOpaque) { + selectedFillOpaqueBin[selectedFillOpaqueBinLen++] = drawable; + } - if (drawable.edges && edgesEnabled) { - if (renderFlags.edgesOpaque) { - normalEdgesOpaqueBin[normalEdgesOpaqueBinLen++] = drawable; - } + if (drawable.edges && edgesEnabled) { + if (renderFlags.edgesOpaque) { + normalEdgesOpaqueBin[normalEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.edgesTransparent) { - normalEdgesTransparentBin[normalEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.edgesTransparent) { + normalEdgesTransparentBin[normalEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.selectedEdgesTransparent) { - selectedEdgesTransparentBin[selectedEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.selectedEdgesTransparent) { + selectedEdgesTransparentBin[selectedEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.selectedEdgesOpaque) { - selectedEdgesOpaqueBin[selectedEdgesOpaqueBinLen++] = drawable; - } + if (renderFlags.selectedEdgesOpaque) { + selectedEdgesOpaqueBin[selectedEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.xrayedEdgesTransparent) { - xrayEdgesTransparentBin[xrayEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.xrayedEdgesTransparent) { + xrayEdgesTransparentBin[xrayEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.xrayedEdgesOpaque) { - xrayEdgesOpaqueBin[xrayEdgesOpaqueBinLen++] = drawable; - } + if (renderFlags.xrayedEdgesOpaque) { + xrayEdgesOpaqueBin[xrayEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.highlightedEdgesTransparent) { - highlightedEdgesTransparentBin[highlightedEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.highlightedEdgesTransparent) { + highlightedEdgesTransparentBin[highlightedEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.highlightedEdgesOpaque) { - highlightedEdgesOpaqueBin[highlightedEdgesOpaqueBinLen++] = drawable; - } - } + if (renderFlags.highlightedEdgesOpaque) { + highlightedEdgesOpaqueBin[highlightedEdgesOpaqueBinLen++] = drawable; } } } @@ -19646,7 +19650,7 @@ const Renderer$1 = function (scene, options) { math.cross3Vec3(worldRayDir, randomVec3, up); pickViewMatrix = math.lookAtMat4v(worldRayOrigin, look, up, tempMat4b); - // pickProjMatrix = scene.camera.projMatrix; + // pickProjMatrix = scene.camera.projMatrix; pickProjMatrix = scene.camera.ortho.matrix; pickResult.origin = worldRayOrigin; @@ -31601,9 +31605,9 @@ class Scene extends Component { * @param {Number[]} [params.matrix] 4x4 transformation matrix to define the World-space ray origin and direction, as an alternative to ````origin```` and ````direction````. * @param {String[]} [params.includeEntities] IDs of {@link Entity}s to restrict picking to. When given, ignores {@link Entity}s whose IDs are not in this list. * @param {String[]} [params.excludeEntities] IDs of {@link Entity}s to ignore. When given, will pick *through* these {@link Entity}s, as if they were not there. - * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels - * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. - * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. + * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels. + * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. Only works when `canvasPos` given. + * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. Only works when `canvasPos` given. * @param {PickResult} [pickResult] Holds the results of the pick attempt. Will use the Scene's singleton PickResult if you don't supply your own. * @returns {PickResult} Holds results of the pick attempt, returned when an {@link Entity} is picked, else null. See method comments for description. */ @@ -31614,6 +31618,11 @@ class Scene extends Component { return null; } + if ((params.snapToVertex || params.snapToEdge) && !params.canvasPos) { + this.error("Scene.snapPick() `canvasPos` parameter expected for `snapToVertex:true` or `snapToEdge:true`"); + return; + } + params = params || {}; params.pickSurface = params.pickSurface || params.rayPick; // Backwards compatibility @@ -31661,7 +31670,7 @@ class Scene extends Component { /** * @param {Object} params Picking parameters. - * @param {Number[]} [params.canvasPos] Canvas-space coordinates. When ray-picking, this will override the **origin** and ** direction** parameters and will cause the ray to be fired through the canvas at this position, directly along the negative View-space Z-axis. + * @param {Number[]} params.canvasPos Canvas-space coordinates. * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. @@ -31672,6 +31681,10 @@ class Scene extends Component { this._warnSnapPickDeprecated = true; this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead"); } + if (!params.canvasPos) { + this.error("Scene.snapPick() canvasPos parameter expected"); + return; + } return this._renderer.snapPick( params.canvasPos, params.snapRadius || 30, @@ -37734,11 +37747,16 @@ class Mesh extends Component { * @param {EmphasisMaterial} [cfg.highlightMaterial] {@link EmphasisMaterial} to define the xrayed appearance for this Mesh. Inherits {@link Scene#highlightMaterial} by default. * @param {EmphasisMaterial} [cfg.selectedMaterial] {@link EmphasisMaterial} to define the selected appearance for this Mesh. Inherits {@link Scene#selectedMaterial} by default. * @param {EmphasisMaterial} [cfg.edgeMaterial] {@link EdgeMaterial} to define the appearance of enhanced edges for this Mesh. Inherits {@link Scene#edgeMaterial} by default. + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this mESH. This is used to control the order in which + * mESHES are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. */ constructor(owner, cfg = {}) { super(owner, cfg); + this.renderOrder = cfg.renderOrder || 0; + /** * ID of the corresponding object within the originating system, if any. * @@ -82327,11 +82345,16 @@ class SceneModel extends Component { * represent the returned model. Set false to always use vertex buffer objects (VBOs). Note that DTX is only applicable * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this SceneModel. This is used to control the order in which + * SceneModels are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. */ constructor(owner, cfg = {}) { super(owner, cfg); + this.renderOrder = cfg.renderOrder || 0; + this._dtxEnabled = this.scene.dtxEnabled && (cfg.dtxEnabled !== false); this._enableVertexWelding = false; // Not needed for most objects, and very expensive, so disabled @@ -84398,6 +84421,7 @@ class SceneModel extends Component { _getVBOBatchingLayer(cfg) { const model = this; const origin = cfg.origin; + cfg.renderLayer || 0; const positionsDecodeHash = cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary ? this._createHashStringFromMatrix(cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary) : "-"; @@ -84884,7 +84908,7 @@ class SceneModel extends Component { // -------------- RENDERING --------------------------------------------------------------------------------------- /** @private */ - drawColorOpaque(frameCtx) { + drawColorOpaque(frameCtx, layerList) { const renderFlags = this.renderFlags; for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) { const layerIndex = renderFlags.visibleLayers[i]; diff --git a/dist/xeokit-sdk.es.js b/dist/xeokit-sdk.es.js index 72e07f080..f319d5978 100644 --- a/dist/xeokit-sdk.es.js +++ b/dist/xeokit-sdk.es.js @@ -10759,7 +10759,7 @@ class Marker extends Component { this.scene.camera.off(this._onCameraProjMatrix); if (this._entity) { if (this._onEntityDestroyed !== null) { - this._entity.off(this._onEntityDestroyed); + this._entity.model.off(this._onEntityDestroyed); } if (this._onEntityModelDestroyed !== null) { this._entity.model.off(this._onEntityModelDestroyed); @@ -18731,6 +18731,9 @@ const Renderer$1 = function (scene, options) { let drawableTypeInfo = {}; let drawables = {}; + let postSortDrawableList = []; + let postCullDrawableList = []; + let drawableListDirty = true; let stateSortDirty = true; let imageDirty = true; @@ -18956,28 +18959,38 @@ const Renderer$1 = function (scene, options) { const drawableInfo = drawableTypeInfo[type]; if (drawableInfo.isStateSortable) { drawableInfo.drawableListPreCull.sort(drawableInfo.stateSortCompare); + + drawableInfo.drawableList = drawableInfo.drawableListPreCull; } } } - } - - function cullDrawableList() { + let lenDrawableList = 0; for (let type in drawableTypeInfo) { if (drawableTypeInfo.hasOwnProperty(type)) { const drawableInfo = drawableTypeInfo[type]; const drawableListPreCull = drawableInfo.drawableListPreCull; - const drawableList = drawableInfo.drawableList; - let lenDrawableList = 0; for (let i = 0, len = drawableListPreCull.length; i < len; i++) { const drawable = drawableListPreCull[i]; - drawable.rebuildRenderFlags(); - if (!drawable.renderFlags.culled) { - drawableList[lenDrawableList++] = drawable; - } + postSortDrawableList[lenDrawableList++] = drawable; } - drawableList.length = lenDrawableList; } } + postSortDrawableList.length = lenDrawableList; + postSortDrawableList.sort((a, b) => { + return a.renderOrder - b.renderOrder; + }); + } + + function cullDrawableList() { + let lenDrawableList = 0; + for (let i = 0, len = postSortDrawableList.length; i < len; i++) { + const drawable = postSortDrawableList[i]; + drawable.rebuildRenderFlags(); + if (!drawable.renderFlags.culled) { + postCullDrawableList[lenDrawableList++] = drawable; + } + } + postCullDrawableList.length = lenDrawableList; } function draw(params) { @@ -19210,7 +19223,6 @@ const Renderer$1 = function (scene, options) { } let i; - let len; let drawable; const startTime = Date.now(); @@ -19243,93 +19255,85 @@ const Renderer$1 = function (scene, options) { // Render normal opaque solids, defer others to bins to render after //------------------------------------------------------------------------------------------------------ - for (let type in drawableTypeInfo) { - if (drawableTypeInfo.hasOwnProperty(type)) { - - const drawableInfo = drawableTypeInfo[type]; - const drawableList = drawableInfo.drawableList; - - for (i = 0, len = drawableList.length; i < len; i++) { + for (let i = 0, len = postCullDrawableList.length; i < len; i++) { - drawable = drawableList[i]; + drawable = postCullDrawableList[i]; - if (drawable.culled === true || drawable.visible === false) { - continue; - } + if (drawable.culled === true || drawable.visible === false) { + continue; + } - const renderFlags = drawable.renderFlags; + const renderFlags = drawable.renderFlags; - if (renderFlags.colorOpaque) { - if (saoEnabled && saoPossible && drawable.saoEnabled) { - normalDrawSAOBin[normalDrawSAOBinLen++] = drawable; - } else { - drawable.drawColorOpaque(frameCtx); - } - } + if (renderFlags.colorOpaque) { + if (saoEnabled && saoPossible && drawable.saoEnabled) { + normalDrawSAOBin[normalDrawSAOBinLen++] = drawable; + } else { + drawable.drawColorOpaque(frameCtx); + } + } - if (transparentEnabled) { - if (renderFlags.colorTransparent) { - normalFillTransparentBin[normalFillTransparentBinLen++] = drawable; - } - } + if (transparentEnabled) { + if (renderFlags.colorTransparent) { + normalFillTransparentBin[normalFillTransparentBinLen++] = drawable; + } + } - if (renderFlags.xrayedSilhouetteTransparent) { - xrayedFillTransparentBin[xrayedFillTransparentBinLen++] = drawable; - } + if (renderFlags.xrayedSilhouetteTransparent) { + xrayedFillTransparentBin[xrayedFillTransparentBinLen++] = drawable; + } - if (renderFlags.xrayedSilhouetteOpaque) { - xrayedFillOpaqueBin[xrayedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.xrayedSilhouetteOpaque) { + xrayedFillOpaqueBin[xrayedFillOpaqueBinLen++] = drawable; + } - if (renderFlags.highlightedSilhouetteTransparent) { - highlightedFillTransparentBin[highlightedFillTransparentBinLen++] = drawable; - } + if (renderFlags.highlightedSilhouetteTransparent) { + highlightedFillTransparentBin[highlightedFillTransparentBinLen++] = drawable; + } - if (renderFlags.highlightedSilhouetteOpaque) { - highlightedFillOpaqueBin[highlightedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.highlightedSilhouetteOpaque) { + highlightedFillOpaqueBin[highlightedFillOpaqueBinLen++] = drawable; + } - if (renderFlags.selectedSilhouetteTransparent) { - selectedFillTransparentBin[selectedFillTransparentBinLen++] = drawable; - } + if (renderFlags.selectedSilhouetteTransparent) { + selectedFillTransparentBin[selectedFillTransparentBinLen++] = drawable; + } - if (renderFlags.selectedSilhouetteOpaque) { - selectedFillOpaqueBin[selectedFillOpaqueBinLen++] = drawable; - } + if (renderFlags.selectedSilhouetteOpaque) { + selectedFillOpaqueBin[selectedFillOpaqueBinLen++] = drawable; + } - if (drawable.edges && edgesEnabled) { - if (renderFlags.edgesOpaque) { - normalEdgesOpaqueBin[normalEdgesOpaqueBinLen++] = drawable; - } + if (drawable.edges && edgesEnabled) { + if (renderFlags.edgesOpaque) { + normalEdgesOpaqueBin[normalEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.edgesTransparent) { - normalEdgesTransparentBin[normalEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.edgesTransparent) { + normalEdgesTransparentBin[normalEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.selectedEdgesTransparent) { - selectedEdgesTransparentBin[selectedEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.selectedEdgesTransparent) { + selectedEdgesTransparentBin[selectedEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.selectedEdgesOpaque) { - selectedEdgesOpaqueBin[selectedEdgesOpaqueBinLen++] = drawable; - } + if (renderFlags.selectedEdgesOpaque) { + selectedEdgesOpaqueBin[selectedEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.xrayedEdgesTransparent) { - xrayEdgesTransparentBin[xrayEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.xrayedEdgesTransparent) { + xrayEdgesTransparentBin[xrayEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.xrayedEdgesOpaque) { - xrayEdgesOpaqueBin[xrayEdgesOpaqueBinLen++] = drawable; - } + if (renderFlags.xrayedEdgesOpaque) { + xrayEdgesOpaqueBin[xrayEdgesOpaqueBinLen++] = drawable; + } - if (renderFlags.highlightedEdgesTransparent) { - highlightedEdgesTransparentBin[highlightedEdgesTransparentBinLen++] = drawable; - } + if (renderFlags.highlightedEdgesTransparent) { + highlightedEdgesTransparentBin[highlightedEdgesTransparentBinLen++] = drawable; + } - if (renderFlags.highlightedEdgesOpaque) { - highlightedEdgesOpaqueBin[highlightedEdgesOpaqueBinLen++] = drawable; - } - } + if (renderFlags.highlightedEdgesOpaque) { + highlightedEdgesOpaqueBin[highlightedEdgesOpaqueBinLen++] = drawable; } } } @@ -19642,7 +19646,7 @@ const Renderer$1 = function (scene, options) { math.cross3Vec3(worldRayDir, randomVec3, up); pickViewMatrix = math.lookAtMat4v(worldRayOrigin, look, up, tempMat4b); - // pickProjMatrix = scene.camera.projMatrix; + // pickProjMatrix = scene.camera.projMatrix; pickProjMatrix = scene.camera.ortho.matrix; pickResult.origin = worldRayOrigin; @@ -31597,9 +31601,9 @@ class Scene extends Component { * @param {Number[]} [params.matrix] 4x4 transformation matrix to define the World-space ray origin and direction, as an alternative to ````origin```` and ````direction````. * @param {String[]} [params.includeEntities] IDs of {@link Entity}s to restrict picking to. When given, ignores {@link Entity}s whose IDs are not in this list. * @param {String[]} [params.excludeEntities] IDs of {@link Entity}s to ignore. When given, will pick *through* these {@link Entity}s, as if they were not there. - * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels - * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. - * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. + * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels. + * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. Only works when `canvasPos` given. + * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. Only works when `canvasPos` given. * @param {PickResult} [pickResult] Holds the results of the pick attempt. Will use the Scene's singleton PickResult if you don't supply your own. * @returns {PickResult} Holds results of the pick attempt, returned when an {@link Entity} is picked, else null. See method comments for description. */ @@ -31610,6 +31614,11 @@ class Scene extends Component { return null; } + if ((params.snapToVertex || params.snapToEdge) && !params.canvasPos) { + this.error("Scene.snapPick() `canvasPos` parameter expected for `snapToVertex:true` or `snapToEdge:true`"); + return; + } + params = params || {}; params.pickSurface = params.pickSurface || params.rayPick; // Backwards compatibility @@ -31657,7 +31666,7 @@ class Scene extends Component { /** * @param {Object} params Picking parameters. - * @param {Number[]} [params.canvasPos] Canvas-space coordinates. When ray-picking, this will override the **origin** and ** direction** parameters and will cause the ray to be fired through the canvas at this position, directly along the negative View-space Z-axis. + * @param {Number[]} params.canvasPos Canvas-space coordinates. * @param {Number} [params.snapRadius=30] The snap radius, in canvas pixels * @param {boolean} [params.snapToVertex=true] Whether to snap to vertex. * @param {boolean} [params.snapToEdge=true] Whether to snap to edge. @@ -31668,6 +31677,10 @@ class Scene extends Component { this._warnSnapPickDeprecated = true; this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead"); } + if (!params.canvasPos) { + this.error("Scene.snapPick() canvasPos parameter expected"); + return; + } return this._renderer.snapPick( params.canvasPos, params.snapRadius || 30, @@ -37730,11 +37743,16 @@ class Mesh extends Component { * @param {EmphasisMaterial} [cfg.highlightMaterial] {@link EmphasisMaterial} to define the xrayed appearance for this Mesh. Inherits {@link Scene#highlightMaterial} by default. * @param {EmphasisMaterial} [cfg.selectedMaterial] {@link EmphasisMaterial} to define the selected appearance for this Mesh. Inherits {@link Scene#selectedMaterial} by default. * @param {EmphasisMaterial} [cfg.edgeMaterial] {@link EdgeMaterial} to define the appearance of enhanced edges for this Mesh. Inherits {@link Scene#edgeMaterial} by default. + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this mESH. This is used to control the order in which + * mESHES are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. */ constructor(owner, cfg = {}) { super(owner, cfg); + this.renderOrder = cfg.renderOrder || 0; + /** * ID of the corresponding object within the originating system, if any. * @@ -82323,11 +82341,16 @@ class SceneModel extends Component { * represent the returned model. Set false to always use vertex buffer objects (VBOs). Note that DTX is only applicable * to non-textured triangle meshes, and that VBOs are always used for meshes that have textures, line segments, or point * primitives. Only works while {@link DTX#enabled} is also ````true````. + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this SceneModel. This is used to control the order in which + * SceneModels are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. */ constructor(owner, cfg = {}) { super(owner, cfg); + this.renderOrder = cfg.renderOrder || 0; + this._dtxEnabled = this.scene.dtxEnabled && (cfg.dtxEnabled !== false); this._enableVertexWelding = false; // Not needed for most objects, and very expensive, so disabled @@ -84394,6 +84417,7 @@ class SceneModel extends Component { _getVBOBatchingLayer(cfg) { const model = this; const origin = cfg.origin; + cfg.renderLayer || 0; const positionsDecodeHash = cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary ? this._createHashStringFromMatrix(cfg.positionsDecodeMatrix || cfg.positionsDecodeBoundary) : "-"; @@ -84880,7 +84904,7 @@ class SceneModel extends Component { // -------------- RENDERING --------------------------------------------------------------------------------------- /** @private */ - drawColorOpaque(frameCtx) { + drawColorOpaque(frameCtx, layerList) { const renderFlags = this.renderFlags; for (let i = 0, len = renderFlags.visibleLayers.length; i < len; i++) { const layerIndex = renderFlags.visibleLayers[i]; diff --git a/dist/xeokit-sdk.es5.js b/dist/xeokit-sdk.es5.js index 8cc3ad275..9549318ab 100644 --- a/dist/xeokit-sdk.es5.js +++ b/dist/xeokit-sdk.es5.js @@ -2755,7 +2755,7 @@ _this14._onEntityModelDestroyed=null;});}else{this._onEntityDestroyed=this._enti * @final */},{key:"visible",get:function get(){return!!this._visible;}/** * Destroys this Marker. - */},{key:"destroy",value:function destroy(){this.fire("destroyed",true);this.scene.camera.off(this._onCameraViewMatrix);this.scene.camera.off(this._onCameraProjMatrix);if(this._entity){if(this._onEntityDestroyed!==null){this._entity.off(this._onEntityDestroyed);}if(this._onEntityModelDestroyed!==null){this._entity.model.off(this._onEntityModelDestroyed);}}this._renderer.removeMarker(this);_get(_getPrototypeOf(Marker.prototype),"destroy",this).call(this);}}]);return Marker;}(Component);var os={isIphoneSafari:function isIphoneSafari(){var userAgent=window.navigator.userAgent;var isIphone=/iPhone/i.test(userAgent);var isSafari=/Safari/i.test(userAgent)&&!/Chrome/i.test(userAgent);return isIphone&&isSafari;}};/** @private */var Wire=/*#__PURE__*/function(){function Wire(parentElement){var _this15=this;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Wire);this._color=cfg.color||"black";this._highlightClass="viewer-ruler-wire-highlighted";this._wire=document.createElement('div');this._wire.className+=this._wire.className?' viewer-ruler-wire':'viewer-ruler-wire';this._wireClickable=document.createElement('div');this._wireClickable.className+=this._wireClickable.className?' viewer-ruler-wire-clickable':'viewer-ruler-wire-clickable';this._thickness=cfg.thickness||1.0;this._thicknessClickable=cfg.thicknessClickable||6.0;this._visible=true;this._culled=false;var wire=this._wire;var wireStyle=wire.style;wireStyle.border="solid "+this._thickness+"px "+this._color;wireStyle.position="absolute";wireStyle["z-index"]=cfg.zIndex===undefined?"2000001":cfg.zIndex;wireStyle.width=0+"px";wireStyle.height=0+"px";wireStyle.visibility="visible";wireStyle.top=0+"px";wireStyle.left=0+"px";wireStyle['-webkit-transform-origin']="0 0";wireStyle['-moz-transform-origin']="0 0";wireStyle['-ms-transform-origin']="0 0";wireStyle['-o-transform-origin']="0 0";wireStyle['transform-origin']="0 0";wireStyle['-webkit-transform']='rotate(0deg)';wireStyle['-moz-transform']='rotate(0deg)';wireStyle['-ms-transform']='rotate(0deg)';wireStyle['-o-transform']='rotate(0deg)';wireStyle['transform']='rotate(0deg)';wireStyle["opacity"]=1.0;wireStyle["pointer-events"]="none";if(cfg.onContextMenu);parentElement.appendChild(wire);var wireClickable=this._wireClickable;var wireClickableStyle=wireClickable.style;wireClickableStyle.border="solid "+this._thicknessClickable+"px "+this._color;wireClickableStyle.position="absolute";wireClickableStyle["z-index"]=cfg.zIndex===undefined?"2000002":cfg.zIndex+1;wireClickableStyle.width=0+"px";wireClickableStyle.height=0+"px";wireClickableStyle.visibility="visible";wireClickableStyle.top=0+"px";wireClickableStyle.left=0+"px";// wireClickableStyle["pointer-events"] = "none"; + */},{key:"destroy",value:function destroy(){this.fire("destroyed",true);this.scene.camera.off(this._onCameraViewMatrix);this.scene.camera.off(this._onCameraProjMatrix);if(this._entity){if(this._onEntityDestroyed!==null){this._entity.model.off(this._onEntityDestroyed);}if(this._onEntityModelDestroyed!==null){this._entity.model.off(this._onEntityModelDestroyed);}}this._renderer.removeMarker(this);_get(_getPrototypeOf(Marker.prototype),"destroy",this).call(this);}}]);return Marker;}(Component);var os={isIphoneSafari:function isIphoneSafari(){var userAgent=window.navigator.userAgent;var isIphone=/iPhone/i.test(userAgent);var isSafari=/Safari/i.test(userAgent)&&!/Chrome/i.test(userAgent);return isIphone&&isSafari;}};/** @private */var Wire=/*#__PURE__*/function(){function Wire(parentElement){var _this15=this;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Wire);this._color=cfg.color||"black";this._highlightClass="viewer-ruler-wire-highlighted";this._wire=document.createElement('div');this._wire.className+=this._wire.className?' viewer-ruler-wire':'viewer-ruler-wire';this._wireClickable=document.createElement('div');this._wireClickable.className+=this._wireClickable.className?' viewer-ruler-wire-clickable':'viewer-ruler-wire-clickable';this._thickness=cfg.thickness||1.0;this._thicknessClickable=cfg.thicknessClickable||6.0;this._visible=true;this._culled=false;var wire=this._wire;var wireStyle=wire.style;wireStyle.border="solid "+this._thickness+"px "+this._color;wireStyle.position="absolute";wireStyle["z-index"]=cfg.zIndex===undefined?"2000001":cfg.zIndex;wireStyle.width=0+"px";wireStyle.height=0+"px";wireStyle.visibility="visible";wireStyle.top=0+"px";wireStyle.left=0+"px";wireStyle['-webkit-transform-origin']="0 0";wireStyle['-moz-transform-origin']="0 0";wireStyle['-ms-transform-origin']="0 0";wireStyle['-o-transform-origin']="0 0";wireStyle['transform-origin']="0 0";wireStyle['-webkit-transform']='rotate(0deg)';wireStyle['-moz-transform']='rotate(0deg)';wireStyle['-ms-transform']='rotate(0deg)';wireStyle['-o-transform']='rotate(0deg)';wireStyle['transform']='rotate(0deg)';wireStyle["opacity"]=1.0;wireStyle["pointer-events"]="none";if(cfg.onContextMenu);parentElement.appendChild(wire);var wireClickable=this._wireClickable;var wireClickableStyle=wireClickable.style;wireClickableStyle.border="solid "+this._thicknessClickable+"px "+this._color;wireClickableStyle.position="absolute";wireClickableStyle["z-index"]=cfg.zIndex===undefined?"2000002":cfg.zIndex+1;wireClickableStyle.width=0+"px";wireClickableStyle.height=0+"px";wireClickableStyle.visibility="visible";wireClickableStyle.top=0+"px";wireClickableStyle.left=0+"px";// wireClickableStyle["pointer-events"] = "none"; wireClickableStyle['-webkit-transform-origin']="0 0";wireClickableStyle['-moz-transform-origin']="0 0";wireClickableStyle['-ms-transform-origin']="0 0";wireClickableStyle['-o-transform-origin']="0 0";wireClickableStyle['transform-origin']="0 0";wireClickableStyle['-webkit-transform']='rotate(0deg)';wireClickableStyle['-moz-transform']='rotate(0deg)';wireClickableStyle['-ms-transform']='rotate(0deg)';wireClickableStyle['-o-transform']='rotate(0deg)';wireClickableStyle['transform']='rotate(0deg)';wireClickableStyle["opacity"]=0.0;wireClickableStyle["pointer-events"]="none";if(cfg.onContextMenu);parentElement.appendChild(wireClickable);if(cfg.onMouseOver){wireClickable.addEventListener('mouseover',function(event){cfg.onMouseOver(event,_this15);});}if(cfg.onMouseLeave){wireClickable.addEventListener('mouseleave',function(event){cfg.onMouseLeave(event,_this15);});}if(cfg.onMouseWheel){wireClickable.addEventListener('wheel',function(event){cfg.onMouseWheel(event,_this15);});}if(cfg.onMouseDown){wireClickable.addEventListener('mousedown',function(event){cfg.onMouseDown(event,_this15);});}if(cfg.onMouseUp){wireClickable.addEventListener('mouseup',function(event){cfg.onMouseUp(event,_this15);});}if(cfg.onMouseMove){wireClickable.addEventListener('mousemove',function(event){cfg.onMouseMove(event,_this15);});}if(cfg.onContextMenu){if(os.isIphoneSafari()){wireClickable.addEventListener('touchstart',function(event){event.preventDefault();if(_this15._timeout){clearTimeout(_this15._timeout);_this15._timeout=null;}_this15._timeout=setTimeout(function(){event.clientX=event.touches[0].clientX;event.clientY=event.touches[0].clientY;cfg.onContextMenu(event,_this15);clearTimeout(_this15._timeout);_this15._timeout=null;},500);});wireClickable.addEventListener('touchend',function(event){event.preventDefault();//stops short touches from calling the timeout if(_this15._timeout){clearTimeout(_this15._timeout);_this15._timeout=null;}});}else{wireClickable.addEventListener('contextmenu',function(event){console.log(event);cfg.onContextMenu(event,_this15);event.preventDefault();event.stopPropagation();console.log("Label context menu");});}}this._x1=0;this._y1=0;this._x2=0;this._y2=0;this._update();}_createClass(Wire,[{key:"visible",get:function get(){return this._wire.style.visibility==="visible";}},{key:"_update",value:function _update(){var length=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2)));var angle=Math.atan2(this._y2-this._y1,this._x2-this._x1)*180.0/Math.PI;var wireStyle=this._wire.style;wireStyle["width"]=Math.round(length)+'px';wireStyle["left"]=Math.round(this._x1)+'px';wireStyle["top"]=Math.round(this._y1)+'px';wireStyle['-webkit-transform']='rotate('+angle+'deg)';wireStyle['-moz-transform']='rotate('+angle+'deg)';wireStyle['-ms-transform']='rotate('+angle+'deg)';wireStyle['-o-transform']='rotate('+angle+'deg)';wireStyle['transform']='rotate('+angle+'deg)';var wireClickableStyle=this._wireClickable.style;wireClickableStyle["width"]=Math.round(length)+'px';wireClickableStyle["left"]=Math.round(this._x1)+'px';wireClickableStyle["top"]=Math.round(this._y1)+'px';wireClickableStyle['-webkit-transform']='rotate('+angle+'deg)';wireClickableStyle['-moz-transform']='rotate('+angle+'deg)';wireClickableStyle['-ms-transform']='rotate('+angle+'deg)';wireClickableStyle['-o-transform']='rotate('+angle+'deg)';wireClickableStyle['transform']='rotate('+angle+'deg)';}},{key:"setStartAndEnd",value:function setStartAndEnd(x1,y1,x2,y2){this._x1=x1;this._y1=y1;this._x2=x2;this._y2=y2;this._update();}},{key:"setColor",value:function setColor(color){this._color=color||"black";this._wire.style.border="solid "+this._thickness+"px "+this._color;}},{key:"setOpacity",value:function setOpacity(opacity){this._wire.style.opacity=opacity;}},{key:"setVisible",value:function setVisible(visible){if(this._visible===visible){return;}this._visible=!!visible;this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden";}},{key:"setCulled",value:function setCulled(culled){if(this._culled===culled){return;}this._culled=!!culled;this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden";}},{key:"setClickable",value:function setClickable(clickable){this._wireClickable.style["pointer-events"]=clickable?"all":"none";}},{key:"setHighlighted",value:function setHighlighted(highlighted){if(this._highlighted===highlighted){return;}this._highlighted=!!highlighted;if(this._highlighted){this._wire.classList.add(this._highlightClass);}else{this._wire.classList.remove(this._highlightClass);}}},{key:"destroy",value:function destroy(visible){if(this._wire.parentElement){this._wire.parentElement.removeChild(this._wire);}if(this._wireClickable.parentElement){this._wireClickable.parentElement.removeChild(this._wireClickable);}}}]);return Wire;}();/** @private */var Dot=/*#__PURE__*/function(){function Dot(parentElement){var _this16=this;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Dot);this._highlightClass="viewer-ruler-dot-highlighted";this._x=0;this._y=0;this._dot=document.createElement('div');this._dot.className+=this._dot.className?' viewer-ruler-dot':'viewer-ruler-dot';this._dotClickable=document.createElement('div');this._dotClickable.className+=this._dotClickable.className?' viewer-ruler-dot-clickable':'viewer-ruler-dot-clickable';this._visible=!!cfg.visible;this._culled=false;var dot=this._dot;var dotStyle=dot.style;dotStyle["border-radius"]=25+"px";dotStyle.border="solid 2px white";dotStyle.background="lightgreen";dotStyle.position="absolute";dotStyle["z-index"]=cfg.zIndex===undefined?"40000005":cfg.zIndex;dotStyle.width=8+"px";dotStyle.height=8+"px";dotStyle.visibility=cfg.visible!==false?"visible":"hidden";dotStyle.top=0+"px";dotStyle.left=0+"px";dotStyle["box-shadow"]="0 2px 5px 0 #182A3D;";dotStyle["opacity"]=1.0;dotStyle["pointer-events"]="none";if(cfg.onContextMenu);parentElement.appendChild(dot);var dotClickable=this._dotClickable;var dotClickableStyle=dotClickable.style;dotClickableStyle["border-radius"]=35+"px";dotClickableStyle.border="solid 10px white";dotClickableStyle.position="absolute";dotClickableStyle["z-index"]=cfg.zIndex===undefined?"40000007":cfg.zIndex+1;dotClickableStyle.width=8+"px";dotClickableStyle.height=8+"px";dotClickableStyle.visibility="visible";dotClickableStyle.top=0+"px";dotClickableStyle.left=0+"px";dotClickableStyle["opacity"]=0.0;dotClickableStyle["pointer-events"]="none";if(cfg.onContextMenu);parentElement.appendChild(dotClickable);dotClickable.addEventListener('click',function(event){parentElement.dispatchEvent(new MouseEvent('mouseover',event));});if(cfg.onMouseOver){dotClickable.addEventListener('mouseover',function(event){cfg.onMouseOver(event,_this16);parentElement.dispatchEvent(new MouseEvent('mouseover',event));});}if(cfg.onMouseLeave){dotClickable.addEventListener('mouseleave',function(event){cfg.onMouseLeave(event,_this16);});}if(cfg.onMouseWheel){dotClickable.addEventListener('wheel',function(event){cfg.onMouseWheel(event,_this16);});}if(cfg.onMouseDown){dotClickable.addEventListener('mousedown',function(event){cfg.onMouseDown(event,_this16);});}if(cfg.onMouseUp){dotClickable.addEventListener('mouseup',function(event){cfg.onMouseUp(event,_this16);});}if(cfg.onMouseMove){dotClickable.addEventListener('mousemove',function(event){cfg.onMouseMove(event,_this16);});}if(cfg.onContextMenu){if(os.isIphoneSafari()){dotClickable.addEventListener('touchstart',function(event){event.preventDefault();if(_this16._timeout){clearTimeout(_this16._timeout);_this16._timeout=null;}_this16._timeout=setTimeout(function(){event.clientX=event.touches[0].clientX;event.clientY=event.touches[0].clientY;cfg.onContextMenu(event,_this16);clearTimeout(_this16._timeout);_this16._timeout=null;},500);});dotClickable.addEventListener('touchend',function(event){event.preventDefault();//stops short touches from calling the timeout if(_this16._timeout){clearTimeout(_this16._timeout);_this16._timeout=null;}});}else{dotClickable.addEventListener('contextmenu',function(event){console.log(event);cfg.onContextMenu(event,_this16);event.preventDefault();event.stopPropagation();console.log("Label context menu");});}}if(cfg.onTouchstart){dotClickable.addEventListener('touchstart',function(event){cfg.onTouchstart(event,_this16);});}if(cfg.onTouchmove){dotClickable.addEventListener('touchmove',function(event){cfg.onTouchmove(event,_this16);});}if(cfg.onTouchend){dotClickable.addEventListener('touchend',function(event){cfg.onTouchend(event,_this16);});}this.setPos(cfg.x||0,cfg.y||0);this.setFillColor(cfg.fillColor);this.setBorderColor(cfg.borderColor);}_createClass(Dot,[{key:"setPos",value:function setPos(x,y){this._x=x;this._y=y;var dotStyle=this._dot.style;dotStyle["left"]=Math.round(x)-4+'px';dotStyle["top"]=Math.round(y)-4+'px';var dotClickableStyle=this._dotClickable.style;dotClickableStyle["left"]=Math.round(x)-9+'px';dotClickableStyle["top"]=Math.round(y)-9+'px';}},{key:"setFillColor",value:function setFillColor(color){this._dot.style.background=color||"lightgreen";}},{key:"setBorderColor",value:function setBorderColor(color){this._dot.style.border="solid 2px"+(color||"black");}},{key:"setOpacity",value:function setOpacity(opacity){this._dot.style.opacity=opacity;}},{key:"setVisible",value:function setVisible(visible){if(this._visible===visible){return;}this._visible=!!visible;this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden";}},{key:"setCulled",value:function setCulled(culled){if(this._culled===culled){return;}this._culled=!!culled;this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden";}},{key:"setClickable",value:function setClickable(clickable){this._dotClickable.style["pointer-events"]=clickable?"all":"none";}},{key:"setHighlighted",value:function setHighlighted(highlighted){if(this._highlighted===highlighted){return;}this._highlighted=!!highlighted;if(this._highlighted){this._dot.classList.add(this._highlightClass);}else{this._dot.classList.remove(this._highlightClass);}}},{key:"destroy",value:function destroy(){this.setVisible(false);if(this._dot.parentElement){this._dot.parentElement.removeChild(this._dot);}if(this._dotClickable.parentElement){this._dotClickable.parentElement.removeChild(this._dotClickable);}}}]);return Dot;}();/** @private */var Label=/*#__PURE__*/function(){function Label(parentElement){var _this17=this;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Label);this._highlightClass="viewer-ruler-label-highlighted";this._prefix=cfg.prefix||"";this._x=0;this._y=0;this._visible=true;this._culled=false;this._label=document.createElement('div');this._label.className+=this._label.className?' viewer-ruler-label':'viewer-ruler-label';this._timeout=null;var label=this._label;var style=label.style;style["border-radius"]=5+"px";style.color="white";style.padding="4px";style.border="solid 1px";style.background="lightgreen";style.position="absolute";style["z-index"]=cfg.zIndex===undefined?"5000005":cfg.zIndex;style.width="auto";style.height="auto";style.visibility="visible";style.top=0+"px";style.left=0+"px";style["pointer-events"]="all";style["opacity"]=1.0;if(cfg.onContextMenu);label.innerText="";parentElement.appendChild(label);this.setPos(cfg.x||0,cfg.y||0);this.setFillColor(cfg.fillColor);this.setBorderColor(cfg.fillColor);this.setText(cfg.text);if(cfg.onMouseOver){label.addEventListener('mouseover',function(event){cfg.onMouseOver(event,_this17);event.preventDefault();});}if(cfg.onMouseLeave){label.addEventListener('mouseleave',function(event){cfg.onMouseLeave(event,_this17);event.preventDefault();});}if(cfg.onMouseWheel){label.addEventListener('wheel',function(event){cfg.onMouseWheel(event,_this17);});}if(cfg.onMouseDown){label.addEventListener('mousedown',function(event){cfg.onMouseDown(event,_this17);event.stopPropagation();});}if(cfg.onMouseUp){label.addEventListener('mouseup',function(event){cfg.onMouseUp(event,_this17);event.stopPropagation();});}if(cfg.onMouseMove){label.addEventListener('mousemove',function(event){cfg.onMouseMove(event,_this17);});}if(cfg.onContextMenu){if(os.isIphoneSafari()){label.addEventListener('touchstart',function(event){event.preventDefault();if(_this17._timeout){clearTimeout(_this17._timeout);_this17._timeout=null;}_this17._timeout=setTimeout(function(){event.clientX=event.touches[0].clientX;event.clientY=event.touches[0].clientY;cfg.onContextMenu(event,_this17);clearTimeout(_this17._timeout);_this17._timeout=null;},500);});label.addEventListener('touchend',function(event){event.preventDefault();//stops short touches from calling the timeout @@ -4760,7 +4760,7 @@ return imageDataCache;}},{key:"unbind",value:function unbind(){var gl=this.gl;gl * @private */var Renderer$1=function Renderer$1(scene,options){options=options||{};var frameCtx=new FrameContext(scene);var canvas=scene.canvas.canvas;/** * @type {WebGL2RenderingContext} - */var gl=scene.canvas.gl;var canvasTransparent=!!options.transparent;var alphaDepthMask=options.alphaDepthMask;var pickIDs=new Map$1({});var drawableTypeInfo={};var drawables={};var drawableListDirty=true;var stateSortDirty=true;var imageDirty=true;var transparentEnabled=true;var edgesEnabled=true;var saoEnabled=true;var pbrEnabled=true;var colorTextureEnabled=true;var renderBufferManager=new RenderBufferManager(scene);var snapshotBound=false;var saoOcclusionRenderer=new SAOOcclusionRenderer(scene);var saoDepthLimitedBlurRenderer=new SAODepthLimitedBlurRenderer(scene);this.scene=scene;this._occlusionTester=null;// Lazy-created in #addMarker() + */var gl=scene.canvas.gl;var canvasTransparent=!!options.transparent;var alphaDepthMask=options.alphaDepthMask;var pickIDs=new Map$1({});var drawableTypeInfo={};var drawables={};var postSortDrawableList=[];var postCullDrawableList=[];var drawableListDirty=true;var stateSortDirty=true;var imageDirty=true;var transparentEnabled=true;var edgesEnabled=true;var saoEnabled=true;var pbrEnabled=true;var colorTextureEnabled=true;var renderBufferManager=new RenderBufferManager(scene);var snapshotBound=false;var saoOcclusionRenderer=new SAOOcclusionRenderer(scene);var saoDepthLimitedBlurRenderer=new SAODepthLimitedBlurRenderer(scene);this.scene=scene;this._occlusionTester=null;// Lazy-created in #addMarker() this.capabilities={astcSupported:!!getExtension(gl,'WEBGL_compressed_texture_astc'),etc1Supported:true,// WebGL2 etc2Supported:!!getExtension(gl,'WEBGL_compressed_texture_etc'),dxtSupported:!!getExtension(gl,'WEBGL_compressed_texture_s3tc'),bptcSupported:!!getExtension(gl,'EXT_texture_compression_bptc'),pvrtcSupported:!!(getExtension(gl,'WEBGL_compressed_texture_pvrtc')||getExtension(gl,'WEBKIT_WEBGL_compressed_texture_pvrtc'))};this.setTransparentEnabled=function(enabled){transparentEnabled=enabled;imageDirty=true;};this.setEdgesEnabled=function(enabled){edgesEnabled=enabled;imageDirty=true;};this.setSAOEnabled=function(enabled){saoEnabled=enabled;imageDirty=true;};this.setPBREnabled=function(enabled){pbrEnabled=enabled;imageDirty=true;};this.setColorTextureEnabled=function(enabled){colorTextureEnabled=enabled;imageDirty=true;};this.needStateSort=function(){stateSortDirty=true;};this.shadowsDirty=function(){};this.imageDirty=function(){imageDirty=true;};this.webglContextLost=function(){};this.webglContextRestored=function(gl){// renderBufferManager.webglContextRestored(gl); saoOcclusionRenderer.init();saoDepthLimitedBlurRenderer.init();imageDirty=true;};/** @@ -4786,19 +4786,19 @@ saoOcclusionRenderer.init();saoDepthLimitedBlurRenderer.init();imageDirty=true;} * @private */this.render=function(params){params=params||{};if(params.force){imageDirty=true;}updateDrawlist();if(imageDirty){draw(params);stats.frame.frameCount++;imageDirty=false;}};function updateDrawlist(){// Prepares state-sorted array of drawables from maps of inserted drawables if(drawableListDirty){buildDrawableList();drawableListDirty=false;stateSortDirty=true;}if(stateSortDirty){sortDrawableList();stateSortDirty=false;imageDirty=true;}if(imageDirty){// Image is usually dirty because the camera moved -cullDrawableList();}}function buildDrawableList(){for(var type in drawableTypeInfo){if(drawableTypeInfo.hasOwnProperty(type)){var drawableInfo=drawableTypeInfo[type];var drawableMap=drawableInfo.drawableMap;var drawableListPreCull=drawableInfo.drawableListPreCull;var lenDrawableList=0;for(var id in drawableMap){if(drawableMap.hasOwnProperty(id)){drawableListPreCull[lenDrawableList++]=drawableMap[id];}}drawableListPreCull.length=lenDrawableList;}}}function sortDrawableList(){for(var type in drawableTypeInfo){if(drawableTypeInfo.hasOwnProperty(type)){var drawableInfo=drawableTypeInfo[type];if(drawableInfo.isStateSortable){drawableInfo.drawableListPreCull.sort(drawableInfo.stateSortCompare);}}}}function cullDrawableList(){for(var type in drawableTypeInfo){if(drawableTypeInfo.hasOwnProperty(type)){var drawableInfo=drawableTypeInfo[type];var drawableListPreCull=drawableInfo.drawableListPreCull;var drawableList=drawableInfo.drawableList;var lenDrawableList=0;for(var _i62=0,len=drawableListPreCull.length;_i621&&arguments[1]!==undefined?arguments[1]:_pickResult;pickResult.reset();updateDrawlist();var look;var pickViewMatrix=null;var pickProjMatrix=null;pickResult.pickSurface=params.pickSurface;if(params.canvasPos){canvasPos[0]=params.canvasPos[0];canvasPos[1]=params.canvasPos[1];pickViewMatrix=scene.camera.viewMatrix;pickProjMatrix=scene.camera.projMatrix;pickResult.canvasPos=params.canvasPos;}else{// Picking with arbitrary World-space ray // Align camera along ray and fire ray through center of canvas if(params.matrix){pickViewMatrix=params.matrix;pickProjMatrix=scene.camera.projMatrix;}else{worldRayOrigin.set(params.origin||[0,0,0]);worldRayDir.set(params.direction||[0,0,1]);look=math.addVec3(worldRayOrigin,worldRayDir,tempVec3a);randomVec3[0]=Math.random();randomVec3[1]=Math.random();randomVec3[2]=Math.random();math.normalizeVec3(randomVec3);math.cross3Vec3(worldRayDir,randomVec3,up);pickViewMatrix=math.lookAtMat4v(worldRayOrigin,look,up,tempMat4b);// pickProjMatrix = scene.camera.projMatrix; -pickProjMatrix=scene.camera.ortho.matrix;pickResult.origin=worldRayOrigin;pickResult.direction=worldRayDir;}canvasPos[0]=canvas.clientWidth*0.5;canvasPos[1]=canvas.clientHeight*0.5;}for(var type in drawableTypeInfo){if(drawableTypeInfo.hasOwnProperty(type)){var drawableList=drawableTypeInfo[type].drawableList;for(var _i66=0,len=drawableList.length;_i660){var pixelNumber=Math.floor(_i71/4);var w=vertexPickBuffer.size[0];var x=pixelNumber%w-Math.floor(w/2);var y=Math.floor(pixelNumber/w)-Math.floor(w/2);var dist=Math.sqrt(Math.pow(x,2)+Math.pow(y,2));snapPickResult.push({x:x,y:y,dist:dist,isVertex:snapToVertex&&snapToEdge?snapPickResultArray[_i71+3]>layerParamsSnap.length/2:snapToVertex,result:[snapPickResultArray[_i71+0],snapPickResultArray[_i71+1],snapPickResultArray[_i71+2],snapPickResultArray[_i71+3]],normal:[snapPickNormalResultArray[_i71+0],snapPickNormalResultArray[_i71+1],snapPickNormalResultArray[_i71+2],snapPickNormalResultArray[_i71+3]],id:[snapPickIdResultArray[_i71+0],snapPickIdResultArray[_i71+1],snapPickIdResultArray[_i71+2],snapPickIdResultArray[_i71+3]]});}}var snappedWorldPos=null;var snappedWorldNormal=null;var snappedPickable=null;var snapType=null;if(snapPickResult.length>0){// vertex snap first, then edge snap +var snapPickResult=[];for(var _i73=0;_i730){var pixelNumber=Math.floor(_i73/4);var w=vertexPickBuffer.size[0];var x=pixelNumber%w-Math.floor(w/2);var y=Math.floor(pixelNumber/w)-Math.floor(w/2);var dist=Math.sqrt(Math.pow(x,2)+Math.pow(y,2));snapPickResult.push({x:x,y:y,dist:dist,isVertex:snapToVertex&&snapToEdge?snapPickResultArray[_i73+3]>layerParamsSnap.length/2:snapToVertex,result:[snapPickResultArray[_i73+0],snapPickResultArray[_i73+1],snapPickResultArray[_i73+2],snapPickResultArray[_i73+3]],normal:[snapPickNormalResultArray[_i73+0],snapPickNormalResultArray[_i73+1],snapPickNormalResultArray[_i73+2],snapPickNormalResultArray[_i73+3]],id:[snapPickIdResultArray[_i73+0],snapPickIdResultArray[_i73+1],snapPickIdResultArray[_i73+2],snapPickIdResultArray[_i73+3]]});}}var snappedWorldPos=null;var snappedWorldNormal=null;var snappedPickable=null;var snapType=null;if(snapPickResult.length>0){// vertex snap first, then edge snap snapPickResult.sort(function(a,b){if(a.isVertex!==b.isVertex){return a.isVertex?-1:1;}else{return a.dist-b.dist;}});snapType=snapPickResult[0].isVertex?"vertex":"edge";var snapPick=snapPickResult[0].result;var snapPickNormal=snapPickResult[0].normal;var snapPickId=snapPickResult[0].id;var pickedLayerParmas=layerParamsSnap[snapPick[3]];var _origin=pickedLayerParmas.origin;var _scale2=pickedLayerParmas.coordinateScale;snappedWorldNormal=math.normalizeVec3([snapPickNormal[0]/math.MAX_INT,snapPickNormal[1]/math.MAX_INT,snapPickNormal[2]/math.MAX_INT]);snappedWorldPos=[snapPick[0]*_scale2[0]+_origin[0],snapPick[1]*_scale2[1]+_origin[1],snapPick[2]*_scale2[2]+_origin[2]];snappedPickable=pickIDs.items[snapPickId[0]+(snapPickId[1]<<8)+(snapPickId[2]<<16)+(snapPickId[3]<<24)];}if(null===worldPos&&null==snappedWorldPos){// If neither regular pick or snap pick, return null return null;}var snappedCanvasPos=null;if(null!==snappedWorldPos){snappedCanvasPos=scene.camera.projectWorldPos(snappedWorldPos);}var snappedEntity=snappedPickable&&snappedPickable.delegatePickedEntity?snappedPickable.delegatePickedEntity():snappedPickable;pickResult.reset();pickResult.snappedToEdge=snapType==="edge";pickResult.snappedToVertex=snapType==="vertex";pickResult.worldPos=snappedWorldPos;pickResult.worldNormal=snappedWorldNormal;pickResult.entity=snappedEntity;pickResult.canvasPos=canvasPos;pickResult.snappedCanvasPos=snappedCanvasPos||canvasPos;return pickResult;};}();function unpackDepth(depthZ){var vec=[depthZ[0]/256.0,depthZ[1]/256.0,depthZ[2]/256.0,depthZ[3]/256.0];var bitShift=[1.0/(256.0*256.0*256.0),1.0/(256.0*256.0),1.0/256.0,1.0];return math.dotVec4(vec,bitShift);}function gpuPickWorldNormal(pickBuffer,pickable,canvasPos,pickViewMatrix,pickProjMatrix,pickResult){var resolutionScale=scene.canvas.resolutionScale;frameCtx.reset();frameCtx.backfaces=true;frameCtx.frontface=true;// "ccw" frameCtx.pickOrigin=pickResult.origin;frameCtx.pickViewMatrix=pickViewMatrix;frameCtx.pickProjMatrix=pickProjMatrix;frameCtx.pickClipPos=[getClipPosX(canvasPos[0]*resolutionScale,gl.drawingBufferWidth),getClipPosY(canvasPos[1]*resolutionScale,gl.drawingBufferHeight)];var pickNormalBuffer=renderBufferManager.getRenderBuffer("pick-normal",{size:[3,3]});pickNormalBuffer.bind(gl.RGBA32I);gl.viewport(0,0,pickNormalBuffer.size[0],pickNormalBuffer.size[1]);gl.enable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND);gl.clear(gl.DEPTH_BUFFER_BIT);gl.clearBufferiv(gl.COLOR,0,new Int32Array([0,0,0,0]));pickable.drawPickNormals(frameCtx);// Draw color-encoded fragment World-space normals @@ -4877,7 +4877,7 @@ var pix=pickNormalBuffer.read(1,1,gl.RGBA_INTEGER,gl.INT,Int32Array,4);pickNorma * Performs an occlusion test for all added {@link Marker}s, updating * their {@link Marker#visible} properties accordingly. */this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){updateDrawlist();this._occlusionTester.bindRenderBuf();frameCtx.reset();frameCtx.backfaces=true;frameCtx.frontface=true;// "ccw" -gl.viewport(0,0,gl.drawingBufferWidth,gl.drawingBufferHeight);gl.clearColor(0,0,0,0);gl.enable(gl.DEPTH_TEST);gl.disable(gl.CULL_FACE);gl.disable(gl.BLEND);gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);for(var type in drawableTypeInfo){if(drawableTypeInfo.hasOwnProperty(type)){var drawableInfo=drawableTypeInfo[type];var drawableList=drawableInfo.drawableList;for(var _i72=0,len=drawableList.length;_i72thresholdDot){continue;}}ia=indicesReverseLookup[edge.index1];ib=indicesReverseLookup[edge.index2];if(!largeIndex&&ia>65535||ib>65535){largeIndex=true;}edgeIndices.push(ia);edgeIndices.push(ib);}return largeIndex?new Uint32Array(edgeIndices):new Uint16Array(edgeIndices);};}();/** * Private geometry compression and decompression utilities. */ /** @@ -6877,7 +6877,7 @@ if(edge.face2!==undefined){normal1=faces[edge.face1].normal;normal2=faces[edge.f */var compressPositions=function(){// http://cg.postech.ac.kr/research/mesh_comp_mobile/mesh_comp_mobile_conference.pdf var translate=math.mat4();var scale=math.mat4();return function(array,min,max){var quantized=new Uint16Array(array.length);var multiplier=new Float32Array([max[0]!==min[0]?65535/(max[0]-min[0]):0,max[1]!==min[1]?65535/(max[1]-min[1]):0,max[2]!==min[2]?65535/(max[2]-min[2]):0]);var i;for(i=0;i2&&arguments[2]!==undefined?arguments[2]:aabb;dest[0]=aabb[0]*decodeMatrix[0]+decodeMatrix[12];dest[1]=aabb[1]*decodeMatrix[5]+decodeMatrix[13];dest[2]=aabb[2]*decodeMatrix[10]+decodeMatrix[14];dest[3]=aabb[3]*decodeMatrix[0]+decodeMatrix[12];dest[4]=aabb[4]*decodeMatrix[5]+decodeMatrix[13];dest[5]=aabb[5]*decodeMatrix[10]+decodeMatrix[14];return dest;}/** * @private - */function decompressPositions(positions,decodeMatrix){var dest=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Float32Array(positions.length);for(var _i75=0,len=positions.length;_i752&&arguments[2]!==undefined?arguments[2]:new Float32Array(positions.length);for(var _i77=0,len=positions.length;_i77bestCos){best=oct;bestCos=currentCos;}oct=octEncodeVec3$1(array,_i76,"floor","ceil");dec=octDecodeVec2$1(oct);currentCos=dot(array,_i76,dec);if(currentCos>bestCos){best=oct;bestCos=currentCos;}oct=octEncodeVec3$1(array,_i76,"ceil","ceil");dec=octDecodeVec2$1(oct);currentCos=dot(array,_i76,dec);if(currentCos>bestCos){best=oct;bestCos=currentCos;}encoded[_i76]=best[0];encoded[_i76+1]=best[1];}return encoded;}/** +best=oct=octEncodeVec3$1(array,_i78,"floor","floor");dec=octDecodeVec2$1(oct);currentCos=bestCos=dot(array,_i78,dec);oct=octEncodeVec3$1(array,_i78,"ceil","floor");dec=octDecodeVec2$1(oct);currentCos=dot(array,_i78,dec);if(currentCos>bestCos){best=oct;bestCos=currentCos;}oct=octEncodeVec3$1(array,_i78,"floor","ceil");dec=octDecodeVec2$1(oct);currentCos=dot(array,_i78,dec);if(currentCos>bestCos){best=oct;bestCos=currentCos;}oct=octEncodeVec3$1(array,_i78,"ceil","ceil");dec=octDecodeVec2$1(oct);currentCos=dot(array,_i78,dec);if(currentCos>bestCos){best=oct;bestCos=currentCos;}encoded[_i78]=best[0];encoded[_i78+1]=best[1];}return encoded;}/** * @private */function octEncodeVec3$1(array,i,xfunc,yfunc){// Oct-encode single normal vector in 2 bytes var x=array[i]/(Math.abs(array[i])+Math.abs(array[i+1])+Math.abs(array[i+2]));var y=array[i+1]/(Math.abs(array[i])+Math.abs(array[i+1])+Math.abs(array[i+2]));if(array[i+2]<0){var tempx=(1-Math.abs(y))*(x>=0?1:-1);var tempy=(1-Math.abs(x))*(y>=0?1:-1);x=tempx;y=tempy;}return new Int8Array([Math[xfunc](x*127.5+(x<0?-1:0)),Math[yfunc](y*127.5+(y<0?-1:0))]);}/** @@ -6904,11 +6904,11 @@ var x=array[i]/(Math.abs(array[i])+Math.abs(array[i+1])+Math.abs(array[i+2]));va * @private */function decompressUV(uv,decodeMatrix,dest){dest[0]=uv[0]*decodeMatrix[0]+decodeMatrix[6];dest[1]=uv[1]*decodeMatrix[4]+decodeMatrix[7];}/** * @private - */function decompressUVs(uvs,decodeMatrix){var dest=arguments.length>2&&arguments[2]!==undefined?arguments[2]:new Float32Array(uvs.length);for(var _i77=0,len=uvs.length;_i772&&arguments[2]!==undefined?arguments[2]:new Float32Array(uvs.length);for(var _i79=0,len=uvs.length;_i79=0?1:-1);y=(1-Math.abs(x))*(y>=0?1:-1);}var length=Math.sqrt(x*x+y*y+z*z);result[0]=x/length;result[1]=y/length;result[2]=z/length;return result;}/** * @private - */function decompressNormals(octs,result){for(var _i78=0,j=0,len=octs.length;_i78=0?1:-1);y=(1-Math.abs(x))*(y>=0?1:-1);}var length=Math.sqrt(x*x+y*y+_z2*_z2);result[j+0]=x/length;result[j+1]=y/length;result[j+2]=_z2/length;j+=3;}return result;}/** + */function decompressNormals(octs,result){for(var _i80=0,j=0,len=octs.length;_i80=0?1:-1);y=(1-Math.abs(x))*(y>=0?1:-1);}var length=Math.sqrt(x*x+y*y+_z2*_z2);result[j+0]=x/length;result[j+1]=y/length;result[j+2]=_z2/length;j+=3;}return result;}/** * @private */var geometryCompressionUtils={getPositionsBounds:getPositionsBounds,createPositionsDecodeMatrix:createPositionsDecodeMatrix$1,compressPositions:compressPositions,compressPosition:compressPosition,decompressPositions:decompressPositions,decompressPosition:decompressPosition,decompressAABB:decompressAABB,getUVBounds:getUVBounds,compressUVs:compressUVs,decompressUVs:decompressUVs,decompressUV:decompressUV,compressNormals:compressNormals,decompressNormals:decompressNormals,decompressNormal:decompressNormal};var memoryStats$1=stats.memory;var tempAABB$3=math.AABB3();/** * @desc A {@link Geometry} that keeps its geometry data in both browser and GPU memory. @@ -8869,7 +8869,7 @@ _this55.preset=cfg.preset;if(cfg.lineWidth!==undefined){_this55.lineWidth=cfg.li */,set:function set(value){value=value||"default";if(this._preset===value){return;}var preset=PRESETS[value];if(!preset){this.error("unsupported preset: '"+value+"' - supported values are "+Object.keys(PRESETS).join(", "));return;}this.lineWidth=preset.lineWidth;this._preset=value;}},{key:"hash",get:function get(){return[""+this.lineWidth].join(";");}/** * Destroys this LinesMaterial. */},{key:"destroy",value:function destroy(){_get(_getPrototypeOf(LinesMaterial.prototype),"destroy",this).call(this);this._state.destroy();}}]);return LinesMaterial;}(Material);// Cached vars to avoid garbage collection -function getEntityIDMap(scene,entityIds){var map={};var entityId;var entity;for(var _i79=0,len=entityIds.length;_i79this._numCachedSectionPlanes?num:this._numCachedSectionPlanes;};}();_this56._sectionPlanesState.setNumCachedSectionPlanes(cfg.numCachedSectionPlanes||0);_this56._lightsState=new function(){var DEFAULT_AMBIENT=math.vec4([0,0,0,0]);var ambientColorIntensity=math.vec4();this.lights=[];this.reflectionMaps=[];this.lightMaps=[];var hash=null;var ambientLight=null;this.getHash=function(){if(hash){return hash;}var hashParts=[];var lights=this.lights;var light;for(var _i82=0,len=lights.length;_i820){hashParts.push("/lm");}if(this.reflectionMaps.length>0){hashParts.push("/rm");}hashParts.push(";");hash=hashParts.join("");return hash;};this.addLight=function(state){this.lights.push(state);ambientLight=null;hash=null;};this.removeLight=function(state){for(var _i83=0,len=this.lights.length;_i83this._numCachedSectionPlanes?num:this._numCachedSectionPlanes;};}();_this56._sectionPlanesState.setNumCachedSectionPlanes(cfg.numCachedSectionPlanes||0);_this56._lightsState=new function(){var DEFAULT_AMBIENT=math.vec4([0,0,0,0]);var ambientColorIntensity=math.vec4();this.lights=[];this.reflectionMaps=[];this.lightMaps=[];var hash=null;var ambientLight=null;this.getHash=function(){if(hash){return hash;}var hashParts=[];var lights=this.lights;var light;for(var _i84=0,len=lights.length;_i840){hashParts.push("/lm");}if(this.reflectionMaps.length>0){hashParts.push("/rm");}hashParts.push(";");hash=hashParts.join("");return hash;};this.addLight=function(state){this.lights.push(state);ambientLight=null;hash=null;};this.removeLight=function(state){for(var _i85=0,len=this.lights.length;_i850;var quantizedGeometry=!!geometryState.compressGeometry;var src=[];src.push("#version 300 es");src.push("// Lambertian drawing vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 colorize;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("uniform vec4 lightAmbient;");src.push("uniform vec4 materialColor;");src.push("uniform vec3 materialEmissive;");if(geometryState.normalsBuf){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");for(var _i94=0,len=lightsState.lights.length;_i94= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}src.push("out vec4 vColor;");if(geometryState.primitiveName==="points"){src.push("uniform float pointSize;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(geometryState.normalsBuf){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(geometryState.normalsBuf){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(geometryState.normalsBuf){src.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");if(geometryState.normalsBuf){for(var _i95=0,_len8=lightsState.lights.length;_i95<_len8;_i95++){var _light=lightsState.lights[_i95];if(_light.type==="ambient"){continue;}if(_light.type==="dir"){if(_light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i95+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i95+", 0.0)).xyz);");}}else if(_light.type==="point"){if(_light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i95+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+_i95+", 0.0)).xyz);");}}else if(_light.type==="spot"){if(_light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i95+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i95+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i95+".rgb * lightColor"+_i95+".a);");}}src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;");// TODO: How to have ambient bright enough for canvas BG but not too bright for scene? + */var DrawShaderSource=function DrawShaderSource(mesh){if(mesh._material._state.type==="LambertMaterial"){this.vertex=buildVertexLambert(mesh);this.fragment=buildFragmentLambert(mesh);}else{this.vertex=buildVertexDraw(mesh);this.fragment=buildFragmentDraw(mesh);}};var TEXTURE_DECODE_FUNCS$1={};TEXTURE_DECODE_FUNCS$1[LinearEncoding]="linearToLinear";TEXTURE_DECODE_FUNCS$1[sRGBEncoding]="sRGBToLinear";function getReceivesShadow(mesh){if(!mesh.receivesShadow){return false;}var lights=mesh.scene._lightsState.lights;if(!lights||lights.length===0){return false;}for(var _i95=0,len=lights.length;_i950;var quantizedGeometry=!!geometryState.compressGeometry;var src=[];src.push("#version 300 es");src.push("// Lambertian drawing vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 colorize;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("uniform vec4 lightAmbient;");src.push("uniform vec4 materialColor;");src.push("uniform vec3 materialEmissive;");if(geometryState.normalsBuf){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");for(var _i96=0,len=lightsState.lights.length;_i96= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}src.push("out vec4 vColor;");if(geometryState.primitiveName==="points"){src.push("uniform float pointSize;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(geometryState.normalsBuf){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(geometryState.normalsBuf){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(geometryState.normalsBuf){src.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");if(geometryState.normalsBuf){for(var _i97=0,_len8=lightsState.lights.length;_i97<_len8;_i97++){var _light=lightsState.lights[_i97];if(_light.type==="ambient"){continue;}if(_light.type==="dir"){if(_light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i97+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i97+", 0.0)).xyz);");}}else if(_light.type==="point"){if(_light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i97+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+_i97+", 0.0)).xyz);");}}else if(_light.type==="spot"){if(_light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i97+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i97+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i97+".rgb * lightColor"+_i97+".a);");}}src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;");// TODO: How to have ambient bright enough for canvas BG but not too bright for scene? if(clipping){src.push("vWorldPosition = worldPosition;");}if(geometryState.primitiveName==="points"){src.push("gl_PointSize = pointSize;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");return src;}function buildFragmentLambert(mesh){var scene=mesh.scene;var sectionPlanesState=scene._sectionPlanesState;mesh._material._state;var geometryState=mesh._geometry._state;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. -var src=[];src.push("#version 300 es");src.push("// Lambertian drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i96=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i96 0.0) { discard; }");src.push("}");}if(geometryState.primitiveName==="points"){src.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;");src.push("float r = dot(cxy, cxy);");src.push("if (r > 1.0) {");src.push(" discard;");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}function buildVertexDraw(mesh){var scene=mesh.scene;mesh._material;var meshState=mesh._state;var sectionPlanesState=scene._sectionPlanesState;var geometryState=mesh._geometry._state;var lightsState=scene._lightsState;var light;var billboard=meshState.billboard;var background=meshState.background;var stationary=meshState.stationary;var texturing=hasTextures(mesh);var normals=hasNormals$1(mesh);var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var receivesShadow=getReceivesShadow(mesh);var quantizedGeometry=!!geometryState.compressGeometry;var src=[];src.push("#version 300 es");src.push("// Drawing vertex shader");src.push("in vec3 position;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("out vec3 vViewPosition;");src.push("uniform vec3 offset;");if(clipping){src.push("out vec4 vWorldPosition;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(lightsState.lightMaps.length>0){src.push("out vec3 vWorldNormal;");}if(normals){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");src.push("out vec3 vViewNormal;");for(var _i98=0,len=lightsState.lights.length;_i98= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}if(texturing){src.push("in vec2 uv;");src.push("out vec2 vUV;");if(quantizedGeometry){src.push("uniform mat3 uvDecodeMatrix;");}}if(geometryState.colors){src.push("in vec4 color;");src.push("out vec4 vColor;");}if(geometryState.primitiveName==="points"){src.push("uniform float pointSize;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}if(receivesShadow){src.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var _i99=0,_len10=lightsState.lights.length;_i99<_len10;_i99++){// Light sources -if(lightsState.lights[_i99].castsShadow){src.push("uniform mat4 shadowViewMatrix"+_i99+";");src.push("uniform mat4 shadowProjMatrix"+_i99+";");src.push("out vec4 vShadowPosFromLight"+_i99+";");}}}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(normals){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}else if(background){src.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(normals){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(normals){src.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; ");if(lightsState.lightMaps.length>0){src.push("vWorldNormal = worldNormal;");}src.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);");src.push("vec3 tmpVec3;");src.push("float lightDist;");for(var _i100=0,_len11=lightsState.lights.length;_i100<_len11;_i100++){// Lights -light=lightsState.lights[_i100];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="world"){src.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+_i100+", 0.0) ).xyz;");src.push("vViewLightReverseDirAndDist"+_i100+" = vec4(-tmpVec3, 0.0);");}}if(light.type==="point"){if(light.space==="world"){src.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+_i100+", 1.0)).xyz - viewPosition.xyz;");src.push("lightDist = abs(length(tmpVec3));");}else{src.push("tmpVec3 = lightPos"+_i100+".xyz - viewPosition.xyz;");src.push("lightDist = abs(length(tmpVec3));");}src.push("vViewLightReverseDirAndDist"+_i100+" = vec4(tmpVec3, lightDist);");}}}if(texturing){if(quantizedGeometry){src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");}else{src.push("vUV = uv;");}}if(geometryState.colors){src.push("vColor = color;");}if(geometryState.primitiveName==="points"){src.push("gl_PointSize = pointSize;");}if(clipping){src.push("vWorldPosition = worldPosition;");}src.push(" vViewPosition = viewPosition.xyz;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(background){src.push("clipPos.z = clipPos.w;");}src.push("gl_Position = clipPos;");if(receivesShadow){src.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);");src.push("vec4 tempx; ");for(var _i101=0,_len12=lightsState.lights.length;_i101<_len12;_i101++){// Light sources -if(lightsState.lights[_i101].castsShadow){src.push("vShadowPosFromLight"+_i101+" = texUnitConverter * shadowProjMatrix"+_i101+" * (shadowViewMatrix"+_i101+" * worldPosition); ");}}}src.push("}");return src;}function buildFragmentDraw(mesh){var scene=mesh.scene;scene.canvas.gl;var material=mesh._material;var geometryState=mesh._geometry._state;var sectionPlanesState=mesh.scene._sectionPlanesState;var lightsState=mesh.scene._lightsState;var materialState=mesh._material._state;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var normals=hasNormals$1(mesh);var uvs=geometryState.uvBuf;var phongMaterial=materialState.type==="PhongMaterial";var metallicMaterial=materialState.type==="MetallicMaterial";var specularMaterial=materialState.type==="SpecularMaterial";var receivesShadow=getReceivesShadow(mesh);scene.gammaInput;// If set, then it expects that all textures and colors are premultiplied gamma. Default is false. +var src=[];src.push("#version 300 es");src.push("// Lambertian drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i98=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i98 0.0) { discard; }");src.push("}");}if(geometryState.primitiveName==="points"){src.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;");src.push("float r = dot(cxy, cxy);");src.push("if (r > 1.0) {");src.push(" discard;");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}function buildVertexDraw(mesh){var scene=mesh.scene;mesh._material;var meshState=mesh._state;var sectionPlanesState=scene._sectionPlanesState;var geometryState=mesh._geometry._state;var lightsState=scene._lightsState;var light;var billboard=meshState.billboard;var background=meshState.background;var stationary=meshState.stationary;var texturing=hasTextures(mesh);var normals=hasNormals$1(mesh);var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var receivesShadow=getReceivesShadow(mesh);var quantizedGeometry=!!geometryState.compressGeometry;var src=[];src.push("#version 300 es");src.push("// Drawing vertex shader");src.push("in vec3 position;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("out vec3 vViewPosition;");src.push("uniform vec3 offset;");if(clipping){src.push("out vec4 vWorldPosition;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(lightsState.lightMaps.length>0){src.push("out vec3 vWorldNormal;");}if(normals){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");src.push("out vec3 vViewNormal;");for(var _i100=0,len=lightsState.lights.length;_i100= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}if(texturing){src.push("in vec2 uv;");src.push("out vec2 vUV;");if(quantizedGeometry){src.push("uniform mat3 uvDecodeMatrix;");}}if(geometryState.colors){src.push("in vec4 color;");src.push("out vec4 vColor;");}if(geometryState.primitiveName==="points"){src.push("uniform float pointSize;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}if(receivesShadow){src.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var _i101=0,_len10=lightsState.lights.length;_i101<_len10;_i101++){// Light sources +if(lightsState.lights[_i101].castsShadow){src.push("uniform mat4 shadowViewMatrix"+_i101+";");src.push("uniform mat4 shadowProjMatrix"+_i101+";");src.push("out vec4 vShadowPosFromLight"+_i101+";");}}}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(normals){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}else if(background){src.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(normals){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(normals){src.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; ");if(lightsState.lightMaps.length>0){src.push("vWorldNormal = worldNormal;");}src.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);");src.push("vec3 tmpVec3;");src.push("float lightDist;");for(var _i102=0,_len11=lightsState.lights.length;_i102<_len11;_i102++){// Lights +light=lightsState.lights[_i102];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="world"){src.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+_i102+", 0.0) ).xyz;");src.push("vViewLightReverseDirAndDist"+_i102+" = vec4(-tmpVec3, 0.0);");}}if(light.type==="point"){if(light.space==="world"){src.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+_i102+", 1.0)).xyz - viewPosition.xyz;");src.push("lightDist = abs(length(tmpVec3));");}else{src.push("tmpVec3 = lightPos"+_i102+".xyz - viewPosition.xyz;");src.push("lightDist = abs(length(tmpVec3));");}src.push("vViewLightReverseDirAndDist"+_i102+" = vec4(tmpVec3, lightDist);");}}}if(texturing){if(quantizedGeometry){src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");}else{src.push("vUV = uv;");}}if(geometryState.colors){src.push("vColor = color;");}if(geometryState.primitiveName==="points"){src.push("gl_PointSize = pointSize;");}if(clipping){src.push("vWorldPosition = worldPosition;");}src.push(" vViewPosition = viewPosition.xyz;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(background){src.push("clipPos.z = clipPos.w;");}src.push("gl_Position = clipPos;");if(receivesShadow){src.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);");src.push("vec4 tempx; ");for(var _i103=0,_len12=lightsState.lights.length;_i103<_len12;_i103++){// Light sources +if(lightsState.lights[_i103].castsShadow){src.push("vShadowPosFromLight"+_i103+" = texUnitConverter * shadowProjMatrix"+_i103+" * (shadowViewMatrix"+_i103+" * worldPosition); ");}}}src.push("}");return src;}function buildFragmentDraw(mesh){var scene=mesh.scene;scene.canvas.gl;var material=mesh._material;var geometryState=mesh._geometry._state;var sectionPlanesState=mesh.scene._sectionPlanesState;var lightsState=mesh.scene._lightsState;var materialState=mesh._material._state;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var normals=hasNormals$1(mesh);var uvs=geometryState.uvBuf;var phongMaterial=materialState.type==="PhongMaterial";var metallicMaterial=materialState.type==="MetallicMaterial";var specularMaterial=materialState.type==="SpecularMaterial";var receivesShadow=getReceivesShadow(mesh);scene.gammaInput;// If set, then it expects that all textures and colors are premultiplied gamma. Default is false. var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. var src=[];src.push("#version 300 es");src.push("// Drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(receivesShadow){src.push("float unpackDepth (vec4 color) {");src.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));");src.push(" return dot(color, bitShift);");src.push("}");}//-------------------------------------------------------------------------------- // GAMMA CORRECTION @@ -10207,8 +10207,8 @@ src.push(" return normalize( tsn * mapN );");src.push("}");}if(uvs&&materia if(normals&&(material._diffuseFresnel||material._specularFresnel||material._alphaFresnel||material._emissiveFresnel||material._reflectivityFresnel)){src.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {");src.push(" float fr = abs(dot(eyeDir, normal));");src.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);");src.push(" return pow(finalFr, power);");src.push("}");if(material._diffuseFresnel){src.push("uniform float diffuseFresnelCenterBias;");src.push("uniform float diffuseFresnelEdgeBias;");src.push("uniform float diffuseFresnelPower;");src.push("uniform vec3 diffuseFresnelCenterColor;");src.push("uniform vec3 diffuseFresnelEdgeColor;");}if(material._specularFresnel){src.push("uniform float specularFresnelCenterBias;");src.push("uniform float specularFresnelEdgeBias;");src.push("uniform float specularFresnelPower;");src.push("uniform vec3 specularFresnelCenterColor;");src.push("uniform vec3 specularFresnelEdgeColor;");}if(material._alphaFresnel){src.push("uniform float alphaFresnelCenterBias;");src.push("uniform float alphaFresnelEdgeBias;");src.push("uniform float alphaFresnelPower;");src.push("uniform vec3 alphaFresnelCenterColor;");src.push("uniform vec3 alphaFresnelEdgeColor;");}if(material._reflectivityFresnel){src.push("uniform float materialSpecularF0FresnelCenterBias;");src.push("uniform float materialSpecularF0FresnelEdgeBias;");src.push("uniform float materialSpecularF0FresnelPower;");src.push("uniform vec3 materialSpecularF0FresnelCenterColor;");src.push("uniform vec3 materialSpecularF0FresnelEdgeColor;");}if(material._emissiveFresnel){src.push("uniform float emissiveFresnelCenterBias;");src.push("uniform float emissiveFresnelEdgeBias;");src.push("uniform float emissiveFresnelPower;");src.push("uniform vec3 emissiveFresnelCenterColor;");src.push("uniform vec3 emissiveFresnelEdgeColor;");}}//-------------------------------------------------------------------------------- // LIGHT SOURCES //-------------------------------------------------------------------------------- -src.push("uniform vec4 lightAmbient;");if(normals){for(var _i102=0,len=lightsState.lights.length;_i102 0.0) { discard; }");src.push("}");}if(geometryState.primitiveName==="points"){src.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;");src.push("float r = dot(cxy, cxy);");src.push("if (r > 1.0) {");src.push(" discard;");src.push("}");}src.push("float occlusion = 1.0;");if(materialState.ambient){src.push("vec3 ambientColor = materialAmbient;");}else{src.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");}if(materialState.diffuse){src.push("vec3 diffuseColor = materialDiffuse;");}else if(materialState.baseColor){src.push("vec3 diffuseColor = materialBaseColor;");}else{src.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");}if(geometryState.colors){src.push("diffuseColor *= vColor.rgb;");}if(materialState.emissive){src.push("vec3 emissiveColor = materialEmissive;");// Emissive default is (0,0,0), so initializing here @@ -10244,9 +10244,9 @@ src.push("float shadow = 1.0;");// if (receivesShadow) { // src.push("float lightDepth2 = clamp(length(lightPos)/40.0, 0.0, 1.0);"); // src.push("float illuminated = VSM(sLightDepth, lightUV, lightDepth2);"); // -src.push("float shadowAcneRemover = 0.007;");src.push("vec3 fragmentDepth;");src.push("float texelSize = 1.0 / 1024.0;");src.push("float amountInLight = 0.0;");src.push("vec3 shadowCoord;");src.push('vec4 rgbaDepth;');src.push("float depth;");for(var _i104=0,_len14=lightsState.lights.length;_i104<_len14;_i104++){var _light2=lightsState.lights[_i104];if(_light2.type==="ambient"){continue;}if(_light2.type==="dir"&&_light2.space==="view"){src.push("viewLightDir = -normalize(lightDir"+_i104+");");}else if(_light2.type==="point"&&_light2.space==="view"){src.push("viewLightDir = normalize(lightPos"+_i104+" - vViewPosition);");//src.push("tmpVec3 = lightPos" + i + ".xyz - viewPosition.xyz;"); +src.push("float shadowAcneRemover = 0.007;");src.push("vec3 fragmentDepth;");src.push("float texelSize = 1.0 / 1024.0;");src.push("float amountInLight = 0.0;");src.push("vec3 shadowCoord;");src.push('vec4 rgbaDepth;');src.push("float depth;");for(var _i106=0,_len14=lightsState.lights.length;_i106<_len14;_i106++){var _light2=lightsState.lights[_i106];if(_light2.type==="ambient"){continue;}if(_light2.type==="dir"&&_light2.space==="view"){src.push("viewLightDir = -normalize(lightDir"+_i106+");");}else if(_light2.type==="point"&&_light2.space==="view"){src.push("viewLightDir = normalize(lightPos"+_i106+" - vViewPosition);");//src.push("tmpVec3 = lightPos" + i + ".xyz - viewPosition.xyz;"); //src.push("lightDist = abs(length(tmpVec3));"); -}else{src.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+_i104+".xyz);");// If normal mapping, the fragment->light vector will be in tangent space +}else{src.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+_i106+".xyz);");// If normal mapping, the fragment->light vector will be in tangent space }if(receivesShadow&&_light2.castsShadow){// if (true) { // src.push('shadowCoord = (vShadowPosFromLight' + i + '.xyz/vShadowPosFromLight' + i + '.w)/2.0 + 0.5;'); // src.push("lightDepth2 = clamp(length(vec3[0.0, 20.0, 20.0])/40.0, 0.0, 1.0);"); @@ -10256,7 +10256,7 @@ src.push("float shadowAcneRemover = 0.007;");src.push("vec3 fragmentDepth;");src // if (false) { // // PCF -src.push("shadow = 0.0;");src.push("fragmentDepth = vShadowPosFromLight"+_i104+".xyz;");src.push("fragmentDepth.z -= shadowAcneRemover;");src.push("for (int x = -3; x <= 3; x++) {");src.push(" for (int y = -3; y <= 3; y++) {");src.push(" float texelDepth = unpackDepth(texture(shadowMap"+_i104+", fragmentDepth.xy + vec2(x, y) * texelSize));");src.push(" if (fragmentDepth.z < texelDepth) {");src.push(" shadow += 1.0;");src.push(" }");src.push(" }");src.push("}");src.push("shadow = shadow / 9.0;");src.push("light.color = lightColor"+_i104+".rgb * (lightColor"+_i104+".a * shadow);");// a is intensity +src.push("shadow = 0.0;");src.push("fragmentDepth = vShadowPosFromLight"+_i106+".xyz;");src.push("fragmentDepth.z -= shadowAcneRemover;");src.push("for (int x = -3; x <= 3; x++) {");src.push(" for (int y = -3; y <= 3; y++) {");src.push(" float texelDepth = unpackDepth(texture(shadowMap"+_i106+", fragmentDepth.xy + vec2(x, y) * texelSize));");src.push(" if (fragmentDepth.z < texelDepth) {");src.push(" shadow += 1.0;");src.push(" }");src.push(" }");src.push("}");src.push("shadow = shadow / 9.0;");src.push("light.color = lightColor"+_i106+".rgb * (lightColor"+_i106+".a * shadow);");// a is intensity // // } // @@ -10273,7 +10273,7 @@ src.push("shadow = 0.0;");src.push("fragmentDepth = vShadowPosFromLight"+_i104+" // // src.push("light.color = lightColor" + i + ".rgb * (lightColor" + i + ".a * shadow);"); // } -}else{src.push("light.color = lightColor"+_i104+".rgb * (lightColor"+_i104+".a );");// a is intensity +}else{src.push("light.color = lightColor"+_i106+".rgb * (lightColor"+_i106+".a );");// a is intensity }src.push("light.direction = viewLightDir;");if(phongMaterial){src.push("computePhongLighting(light, geometry, material, reflectedLight);");}if(specularMaterial||metallicMaterial){src.push("computePBRLighting(light, geometry, material, reflectedLight);");}}//src.push("reflectedLight.diffuse *= shadow;"); // COMBINE TERMS if(phongMaterial){src.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;");}else{src.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;");}}else{//-------------------------------------------------------------------------------- @@ -10287,10 +10287,10 @@ src.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);");src.push("vec3 if(geometryState.id!==this._lastGeometryId){if(this._uPositionsDecodeMatrix){gl.uniformMatrix4fv(this._uPositionsDecodeMatrix,false,geometryState.positionsDecodeMatrix);}if(this._uUVDecodeMatrix){gl.uniformMatrix3fv(this._uUVDecodeMatrix,false,geometryState.uvDecodeMatrix);}if(this._aPosition){this._aPosition.bindArrayBuffer(geometryState.positionsBuf);frameCtx.bindArray++;}if(this._aNormal){this._aNormal.bindArrayBuffer(geometryState.normalsBuf);frameCtx.bindArray++;}if(this._aUV){this._aUV.bindArrayBuffer(geometryState.uvBuf);frameCtx.bindArray++;}if(this._aColor){this._aColor.bindArrayBuffer(geometryState.colorsBuf);frameCtx.bindArray++;}if(this._aFlags){this._aFlags.bindArrayBuffer(geometryState.flagsBuf);frameCtx.bindArray++;}if(geometryState.indicesBuf){geometryState.indicesBuf.bind();frameCtx.bindArray++;}this._lastGeometryId=geometryState.id;}// Draw (indices bound in prev step) if(geometryState.indicesBuf){gl.drawElements(geometryState.primitive,geometryState.indicesBuf.numItems,geometryState.indicesBuf.itemType,0);frameCtx.drawElements++;}else if(geometryState.positions){gl.drawArrays(gl.TRIANGLES,0,geometryState.positions.numItems);frameCtx.drawArrays++;}if(background){gl.depthFunc(gl.LESS);}};DrawRenderer.prototype._allocate=function(mesh){var scene=mesh.scene;var gl=scene.canvas.gl;var material=mesh._material;var lightsState=scene._lightsState;var sectionPlanesState=scene._sectionPlanesState;var materialState=mesh._material._state;this._program=new Program(gl,this._shaderSource);if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uPositionsDecodeMatrix=program.getLocation("positionsDecodeMatrix");this._uUVDecodeMatrix=program.getLocation("uvDecodeMatrix");this._uModelMatrix=program.getLocation("modelMatrix");this._uModelNormalMatrix=program.getLocation("modelNormalMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uViewNormalMatrix=program.getLocation("viewNormalMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uGammaFactor=program.getLocation("gammaFactor");this._uLightAmbient=[];this._uLightColor=[];this._uLightDir=[];this._uLightPos=[];this._uLightAttenuation=[];this._uShadowViewMatrix=[];this._uShadowProjMatrix=[];if(scene.logarithmicDepthBufferEnabled){this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}var lights=lightsState.lights;var light;for(var i=0,len=lights.length;i0){this._uLightMap="lightMap";}if(lightsState.reflectionMaps.length>0){this._uReflectionMap="reflectionMap";}this._uSectionPlanes=[];var sectionPlanes=sectionPlanesState.sectionPlanes;for(var i=0,len=sectionPlanes.length;i0&&lightsState.lightMaps[0].texture&&this._uLightMap){program.bindTexture(this._uLightMap,lightsState.lightMaps[0].texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;frameCtx.bindTexture++;}if(lightsState.reflectionMaps.length>0&&lightsState.reflectionMaps[0].texture&&this._uReflectionMap){program.bindTexture(this._uReflectionMap,lightsState.reflectionMaps[0].texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;frameCtx.bindTexture++;}if(this._uGammaFactor){gl.uniform1f(this._uGammaFactor,scene.gammaFactor);}this._baseTextureUnit=frameCtx.textureUnit;};/** * @private - */var EmphasisFillShaderSource=/*#__PURE__*/_createClass(function EmphasisFillShaderSource(mesh){_classCallCheck(this,EmphasisFillShaderSource);this.vertex=buildVertex$5(mesh);this.fragment=buildFragment$5(mesh);});function buildVertex$5(mesh){var scene=mesh.scene;var lightsState=scene._lightsState;var normals=hasNormals(mesh);var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var billboard=mesh._state.billboard;var stationary=mesh._state.stationary;var src=[];src.push("#version 300 es");src.push("// EmphasisFillShaderSource vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 colorize;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("uniform vec4 lightAmbient;");src.push("uniform vec4 fillColor;");if(normals){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");for(var _i105=0,len=lightsState.lights.length;_i105= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}src.push("out vec4 vColor;");if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(normals){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(normals){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(normals){src.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");if(normals){for(var _i106=0,_len15=lightsState.lights.length;_i106<_len15;_i106++){var _light3=lightsState.lights[_i106];if(_light3.type==="ambient"){continue;}if(_light3.type==="dir"){if(_light3.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i106+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i106+", 0.0)).xyz);");}}else if(_light3.type==="point"){if(_light3.space==="view"){src.push("viewLightDir = normalize(lightPos"+_i106+" - viewPosition.xyz);");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+_i106+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i106+".rgb * lightColor"+_i106+".a);");}}// TODO: A blending mode for emphasis materials, to select add/multiply/mix + */var EmphasisFillShaderSource=/*#__PURE__*/_createClass(function EmphasisFillShaderSource(mesh){_classCallCheck(this,EmphasisFillShaderSource);this.vertex=buildVertex$5(mesh);this.fragment=buildFragment$5(mesh);});function buildVertex$5(mesh){var scene=mesh.scene;var lightsState=scene._lightsState;var normals=hasNormals(mesh);var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var billboard=mesh._state.billboard;var stationary=mesh._state.stationary;var src=[];src.push("#version 300 es");src.push("// EmphasisFillShaderSource vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 colorize;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("uniform vec4 lightAmbient;");src.push("uniform vec4 fillColor;");if(normals){src.push("in vec3 normal;");src.push("uniform mat4 modelNormalMatrix;");src.push("uniform mat4 viewNormalMatrix;");for(var _i107=0,len=lightsState.lights.length;_i107= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");}}src.push("out vec4 vColor;");if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}if(normals){if(quantizedGeometry){src.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); ");}else{src.push("vec4 localNormal = vec4(normal, 0.0); ");}src.push("mat4 modelNormalMatrix2 = modelNormalMatrix;");src.push("mat4 viewNormalMatrix2 = viewNormalMatrix;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");if(normals){src.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;");src.push("billboard(modelNormalMatrix2);");src.push("billboard(viewNormalMatrix2);");src.push("billboard(modelViewNormalMatrix);");}src.push("worldPosition = modelMatrix2 * localPosition;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}if(normals){src.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");if(normals){for(var _i108=0,_len15=lightsState.lights.length;_i108<_len15;_i108++){var _light3=lightsState.lights[_i108];if(_light3.type==="ambient"){continue;}if(_light3.type==="dir"){if(_light3.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i108+");");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+_i108+", 0.0)).xyz);");}}else if(_light3.type==="point"){if(_light3.space==="view"){src.push("viewLightDir = normalize(lightPos"+_i108+" - viewPosition.xyz);");}else{src.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+_i108+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i108+".rgb * lightColor"+_i108+".a);");}}// TODO: A blending mode for emphasis materials, to select add/multiply/mix //src.push("vColor = vec4((mix(reflectedColor, fillColor.rgb, 0.7)), fillColor.a);"); src.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);");//src.push("vColor = vec4(reflectedColor + fillColor.rgb, fillColor.a);"); -if(clipping){src.push("vWorldPosition = worldPosition;");}if(mesh._geometry._state.primitiveName==="points"){src.push("gl_PointSize = pointSize;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");return src;}function hasNormals(mesh){var primitive=mesh._geometry._state.primitiveName;if((mesh._geometry._state.autoVertexNormals||mesh._geometry._state.normalsBuf)&&(primitive==="triangles"||primitive==="triangle-strip"||primitive==="triangle-fan")){return true;}return false;}function buildFragment$5(mesh){var scene=mesh.scene;var sectionPlanesState=mesh.scene._sectionPlanesState;var gammaOutput=mesh.scene.gammaOutput;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Lambertian drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(gammaOutput){src.push("uniform float gammaFactor;");src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i107=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i107 0.0) { discard; }");src.push("}");}if(mesh._geometry._state.primitiveName==="points"){src.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;");src.push("float r = dot(cxy, cxy);");src.push("if (r > 1.0) {");src.push(" discard;");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}/** +if(clipping){src.push("vWorldPosition = worldPosition;");}if(mesh._geometry._state.primitiveName==="points"){src.push("gl_PointSize = pointSize;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");return src;}function hasNormals(mesh){var primitive=mesh._geometry._state.primitiveName;if((mesh._geometry._state.autoVertexNormals||mesh._geometry._state.normalsBuf)&&(primitive==="triangles"||primitive==="triangle-strip"||primitive==="triangle-fan")){return true;}return false;}function buildFragment$5(mesh){var scene=mesh.scene;var sectionPlanesState=mesh.scene._sectionPlanesState;var gammaOutput=mesh.scene.gammaOutput;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Lambertian drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(gammaOutput){src.push("uniform float gammaFactor;");src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i109=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i109 0.0) { discard; }");src.push("}");}if(mesh._geometry._state.primitiveName==="points"){src.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;");src.push("float r = dot(cxy, cxy);");src.push("if (r > 1.0) {");src.push(" discard;");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}/** * @author xeolabs / https://github.com/xeolabs */var ids$1=new Map$1({});var tempVec3a$H=math.vec3();/** * @private @@ -10298,15 +10298,15 @@ if(clipping){src.push("vWorldPosition = worldPosition;");}if(mesh._geometry._sta mesh.scene._sectionPlanesState.getHash(),!!mesh._geometry._state.normalsBuf?"n":"",mesh._geometry._state.compressGeometry?"cp":"",mesh._state.hash].join(";");var renderer=xrayFillRenderers[hash];if(!renderer){renderer=new EmphasisFillRenderer(hash,mesh);xrayFillRenderers[hash]=renderer;stats.memory.programs++;}renderer._useCount++;return renderer;};EmphasisFillRenderer.prototype.put=function(){if(--this._useCount===0){ids$1.removeItem(this.id);if(this._program){this._program.destroy();}delete xrayFillRenderers[this._hash];stats.memory.programs--;}};EmphasisFillRenderer.prototype.webglContextRestored=function(){this._program=null;};EmphasisFillRenderer.prototype.drawMesh=function(frameCtx,mesh,mode){if(!this._program){this._allocate(mesh);}var scene=this._scene;var camera=scene.camera;var gl=scene.canvas.gl;var materialState=mode===0?mesh._xrayMaterial._state:mode===1?mesh._highlightMaterial._state:mesh._selectedMaterial._state;var meshState=mesh._state;var geometryState=mesh._geometry._state;var origin=mesh.origin;if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx);}gl.uniformMatrix4fv(this._uViewMatrix,false,origin?frameCtx.getRTCViewMatrix(meshState.originHash,origin):camera.viewMatrix);gl.uniformMatrix4fv(this._uViewNormalMatrix,false,camera.viewNormalMatrix);if(meshState.clippable){var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var billboard=mesh._state.billboard;var stationary=mesh._state.stationary;var src=[];src.push("#version 300 es");src.push("// Edges drawing vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 edgeColor;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("out vec4 vColor;");if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}src.push("vColor = edgeColor;");if(clipping){src.push("vWorldPosition = worldPosition;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");return src;}function buildFragment$4(mesh){var scene=mesh.scene;var sectionPlanesState=mesh.scene._sectionPlanesState;var gammaOutput=mesh.scene.gammaOutput;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Edges drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(gammaOutput){src.push("uniform float gammaFactor;");src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i112=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i112 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}/** + */var EmphasisEdgesShaderSource=/*#__PURE__*/_createClass(function EmphasisEdgesShaderSource(mesh){_classCallCheck(this,EmphasisEdgesShaderSource);this.vertex=buildVertex$4(mesh);this.fragment=buildFragment$4(mesh);});function buildVertex$4(mesh){var scene=mesh.scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var billboard=mesh._state.billboard;var stationary=mesh._state.stationary;var src=[];src.push("#version 300 es");src.push("// Edges drawing vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec4 edgeColor;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("out vec4 vColor;");if(billboard==="spherical"||billboard==="cylindrical"){src.push("void billboard(inout mat4 mat) {");src.push(" mat[0][0] = 1.0;");src.push(" mat[0][1] = 0.0;");src.push(" mat[0][2] = 0.0;");if(billboard==="spherical"){src.push(" mat[1][0] = 0.0;");src.push(" mat[1][1] = 1.0;");src.push(" mat[1][2] = 0.0;");}src.push(" mat[2][0] = 0.0;");src.push(" mat[2][1] = 0.0;");src.push(" mat[2][2] =1.0;");src.push("}");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}src.push("mat4 viewMatrix2 = viewMatrix;");src.push("mat4 modelMatrix2 = modelMatrix;");if(stationary){src.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");}if(billboard==="spherical"||billboard==="cylindrical"){src.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;");src.push("billboard(modelMatrix2);");src.push("billboard(viewMatrix2);");src.push("billboard(modelViewMatrix);");src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = modelViewMatrix * localPosition;");}else{src.push("worldPosition = modelMatrix2 * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = viewMatrix2 * worldPosition; ");}src.push("vColor = edgeColor;");if(clipping){src.push("vWorldPosition = worldPosition;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");return src;}function buildFragment$4(mesh){var scene=mesh.scene;var sectionPlanesState=mesh.scene._sectionPlanesState;var gammaOutput=mesh.scene.gammaOutput;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Edges drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(gammaOutput){src.push("uniform float gammaFactor;");src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("uniform bool clippable;");for(var _i114=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i114 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(gammaOutput){src.push("outColor = linearToGamma(vColor, gammaFactor);");}else{src.push("outColor = vColor;");}src.push("}");return src;}/** * @author xeolabs / https://github.com/xeolabs */var ids=new Map$1({});var tempVec3a$G=math.vec3();/** * @private */var EmphasisEdgesRenderer=function EmphasisEdgesRenderer(hash,mesh){this.id=ids.addItem({});this._hash=hash;this._scene=mesh.scene;this._useCount=0;this._shaderSource=new EmphasisEdgesShaderSource(mesh);this._allocate(mesh);};var renderers$4={};EmphasisEdgesRenderer.get=function(mesh){var hash=[mesh.scene.id,mesh.scene.gammaOutput?"go":"",// Gamma input not needed mesh.scene._sectionPlanesState.getHash(),mesh._geometry._state.compressGeometry?"cp":"",mesh._state.hash].join(";");var renderer=renderers$4[hash];if(!renderer){renderer=new EmphasisEdgesRenderer(hash,mesh);renderers$4[hash]=renderer;stats.memory.programs++;}renderer._useCount++;return renderer;};EmphasisEdgesRenderer.prototype.put=function(){if(--this._useCount===0){ids.removeItem(this.id);if(this._program){this._program.destroy();}delete renderers$4[this._hash];stats.memory.programs--;}};EmphasisEdgesRenderer.prototype.webglContextRestored=function(){this._program=null;};EmphasisEdgesRenderer.prototype.drawMesh=function(frameCtx,mesh,mode){if(!this._program){this._allocate(mesh);}var scene=this._scene;var camera=scene.camera;var gl=scene.canvas.gl;var materialState;var meshState=mesh._state;var geometry=mesh._geometry;var geometryState=geometry._state;var origin=mesh.origin;if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx);}gl.uniformMatrix4fv(this._uViewMatrix,false,origin?frameCtx.getRTCViewMatrix(meshState.originHash,origin):camera.viewMatrix);if(meshState.clippable){var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex>24&0xFF;var b=pickID>>16&0xFF;var g=pickID>>8&0xFF;var r=pickID&0xFF;gl.uniform4f(this._uPickColor,r/255,g/255,b/255,a/255);gl.uniform2fv(this._uPickClipPos,frameCtx.pickClipPos);if(geometryState.indicesBuf){gl.drawElements(geometryState.primitive,geometryState.indicesBuf.numItems,geometryState.indicesBuf.itemType,0);frameCtx.drawElements++;}else if(geometryState.positions){gl.drawArrays(gl.TRIANGLES,0,geometryState.positions.numItems);}};PickMeshRenderer.prototype._allocate=function(mesh){var scene=mesh.scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._shaderSource);if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uPositionsDecodeMatrix=program.getLocation("positionsDecodeMatrix");this._uModelMatrix=program.getLocation("modelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];var clips=scene._sectionPlanesState.sectionPlanes;for(var _i115=0,len=clips.length;_i115>24&0xFF;var b=pickID>>16&0xFF;var g=pickID>>8&0xFF;var r=pickID&0xFF;gl.uniform4f(this._uPickColor,r/255,g/255,b/255,a/255);gl.uniform2fv(this._uPickClipPos,frameCtx.pickClipPos);if(geometryState.indicesBuf){gl.drawElements(geometryState.primitive,geometryState.indicesBuf.numItems,geometryState.indicesBuf.itemType,0);frameCtx.drawElements++;}else if(geometryState.positions){gl.drawArrays(gl.TRIANGLES,0,geometryState.positions.numItems);}};PickMeshRenderer.prototype._allocate=function(mesh){var scene=mesh.scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._shaderSource);if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uPositionsDecodeMatrix=program.getLocation("positionsDecodeMatrix");this._uModelMatrix=program.getLocation("modelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];var clips=scene._sectionPlanesState.sectionPlanes;for(var _i117=0,len=clips.length;_i1170;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var src=[];src.push('#version 300 es');src.push("// Surface picking vertex shader");src.push("in vec3 position;");src.push("in vec4 color;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec3 offset;");if(clipping){src.push("uniform bool clippable;");src.push("out vec4 vWorldPosition;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy -= pickClipPos;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("out vec4 vColor;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}src.push(" vec4 worldPosition = modelMatrix * localPosition; ");src.push(" worldPosition.xyz = worldPosition.xyz + offset;");src.push(" vec4 viewPosition = viewMatrix * worldPosition;");if(clipping){src.push(" vWorldPosition = worldPosition;");}src.push(" vColor = color;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");return src;}function buildFragment$2(mesh){var scene=mesh.scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Surface picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");src.push("in vec4 vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("uniform bool clippable;");src.push("in vec4 vWorldPosition;");for(var _i116=0;_i116 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}/** + */var PickTriangleShaderSource=/*#__PURE__*/_createClass(function PickTriangleShaderSource(mesh){_classCallCheck(this,PickTriangleShaderSource);this.vertex=buildVertex$2(mesh);this.fragment=buildFragment$2(mesh);});function buildVertex$2(mesh){var scene=mesh.scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var src=[];src.push('#version 300 es');src.push("// Surface picking vertex shader");src.push("in vec3 position;");src.push("in vec4 color;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform vec3 offset;");if(clipping){src.push("uniform bool clippable;");src.push("out vec4 vWorldPosition;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy -= pickClipPos;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("out vec4 vColor;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}src.push(" vec4 worldPosition = modelMatrix * localPosition; ");src.push(" worldPosition.xyz = worldPosition.xyz + offset;");src.push(" vec4 viewPosition = viewMatrix * worldPosition;");if(clipping){src.push(" vWorldPosition = worldPosition;");}src.push(" vColor = color;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");return src;}function buildFragment$2(mesh){var scene=mesh.scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Surface picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");src.push("in vec4 vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("uniform bool clippable;");src.push("in vec4 vWorldPosition;");for(var _i118=0;_i118 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}/** * @author xeolabs / https://github.com/xeolabs */var tempVec3a$E=math.vec3();/** * @private */var PickTriangleRenderer=function PickTriangleRenderer(hash,mesh){this._hash=hash;this._scene=mesh.scene;this._useCount=0;this._shaderSource=new PickTriangleShaderSource(mesh);this._allocate(mesh);};var renderers$2={};PickTriangleRenderer.get=function(mesh){var hash=[mesh.scene.canvas.canvas.id,mesh.scene._sectionPlanesState.getHash(),mesh._geometry._state.compressGeometry?"cp":"",mesh._state.hash].join(";");var renderer=renderers$2[hash];if(!renderer){renderer=new PickTriangleRenderer(hash,mesh);if(renderer.errors){console.log(renderer.errors.join("\n"));return null;}renderers$2[hash]=renderer;stats.memory.programs++;}renderer._useCount++;return renderer;};PickTriangleRenderer.prototype.put=function(){if(--this._useCount===0){if(this._program){this._program.destroy();}delete renderers$2[this._hash];stats.memory.programs--;}};PickTriangleRenderer.prototype.webglContextRestored=function(){this._program=null;};PickTriangleRenderer.prototype.drawMesh=function(frameCtx,mesh){if(!this._program){this._allocate(mesh);}var scene=this._scene;var gl=scene.canvas.gl;var meshState=mesh._state;var materialState=mesh._material._state;var geometry=mesh._geometry;var geometryState=mesh._geometry._state;var origin=mesh.origin;var backfaces=materialState.backfaces;var frontface=materialState.frontface;var project=scene.camera.project;var positionsBuf=geometry._getPickTrianglePositions();var pickColorsBuf=geometry._getPickTriangleColors();this._program.bind();frameCtx.useProgram++;if(scene.logarithmicDepthBufferEnabled){var logDepthBufFC=2.0/(Math.log(project.far+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}gl.uniformMatrix4fv(this._uViewMatrix,false,origin?frameCtx.getRTCPickViewMatrix(meshState.originHash,origin):frameCtx.pickViewMatrix);if(meshState.clippable){var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var renderFlags=mesh.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0;var quantizedGeometry=!!mesh._geometry._state.compressGeometry;var src=[];src.push("// Mesh shadow vertex shader");src.push("in vec3 position;");src.push("uniform mat4 modelMatrix;");src.push("uniform mat4 shadowViewMatrix;");src.push("uniform mat4 shadowProjMatrix;");src.push("uniform vec3 offset;");if(quantizedGeometry){src.push("uniform mat4 positionsDecodeMatrix;");}if(clipping){src.push("out vec4 vWorldPosition;");}src.push("void main(void) {");src.push("vec4 localPosition = vec4(position, 1.0); ");src.push("vec4 worldPosition;");if(quantizedGeometry){src.push("localPosition = positionsDecodeMatrix * localPosition;");}src.push("worldPosition = modelMatrix * localPosition;");src.push("worldPosition.xyz = worldPosition.xyz + offset;");src.push("vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");}src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push("}");return src;}function buildFragment(mesh){var scene=mesh.scene;scene.canvas.gl;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("// Mesh shadow fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("uniform bool clippable;");src.push("in vec4 vWorldPosition;");for(var i=0;i 0.0) { discard; }");src.push("}");}src.push("outColor = encodeFloat(gl_FragCoord.z);");src.push("}");return src;}/** * @private */var ShadowRenderer=function ShadowRenderer(hash,mesh){this._hash=hash;this._shaderSource=new ShadowShaderSource(mesh);this._scene=mesh.scene;this._useCount=0;this._allocate(mesh);};var renderers={};ShadowRenderer.get=function(mesh){var scene=mesh.scene;var hash=[scene.canvas.canvas.id,scene._sectionPlanesState.getHash(),mesh._geometry._state.hash,mesh._state.hash].join(";");var renderer=renderers[hash];if(!renderer){renderer=new ShadowRenderer(hash,mesh);if(renderer.errors){console.log(renderer.errors.join("\n"));return null;}renderers[hash]=renderer;stats.memory.programs++;}renderer._useCount++;return renderer;};ShadowRenderer.prototype.put=function(){if(--this._useCount===0){if(this._program){this._program.destroy();}delete renderers[this._hash];stats.memory.programs--;}};ShadowRenderer.prototype.webglContextRestored=function(){this._program=null;};ShadowRenderer.prototype.drawMesh=function(frame,mesh){if(!this._program){this._allocate(mesh);}var scene=this._scene;var gl=scene.canvas.gl;var materialState=mesh._material._state;var geometryState=mesh._geometry._state;if(frame.lastProgramId!==this._program.id){frame.lastProgramId=this._program.id;this._bindProgram(frame);}if(materialState.id!==this._lastMaterialId){var backfaces=materialState.backfaces;if(frame.backfaces!==backfaces){if(backfaces){gl.disable(gl.CULL_FACE);}else{gl.enable(gl.CULL_FACE);}frame.backfaces=backfaces;}var frontface=materialState.frontface;if(frame.frontface!==frontface){if(frontface){gl.frontFace(gl.CCW);}else{gl.frontFace(gl.CW);}frame.frontface=frontface;}if(frame.lineWidth!==materialState.lineWidth){gl.lineWidth(materialState.lineWidth);frame.lineWidth=materialState.lineWidth;}if(this._uPointSize){gl.uniform1i(this._uPointSize,materialState.pointSize);}this._lastMaterialId=materialState.id;}gl.uniformMatrix4fv(this._uModelMatrix,gl.FALSE,mesh.worldMatrix);if(geometryState.combineGeometry){var vertexBufs=mesh.vertexBufs;if(vertexBufs.id!==this._lastVertexBufsId){if(vertexBufs.positionsBuf&&this._aPosition){this._aPosition.bindArrayBuffer(vertexBufs.positionsBuf,vertexBufs.compressGeometry?gl.UNSIGNED_SHORT:gl.FLOAT);frame.bindArray++;}this._lastVertexBufsId=vertexBufs.id;}}if(this._uClippable){gl.uniform1i(this._uClippable,mesh._state.clippable);}gl.uniform3fv(this._uOffset,mesh._state.offset);if(geometryState.id!==this._lastGeometryId){if(this._uPositionsDecodeMatrix){gl.uniformMatrix4fv(this._uPositionsDecodeMatrix,false,geometryState.positionsDecodeMatrix);}if(geometryState.combineGeometry){// VBOs were bound by the preceding VertexBufs chunk -if(geometryState.indicesBufCombined){geometryState.indicesBufCombined.bind();frame.bindArray++;}}else{if(this._aPosition){this._aPosition.bindArrayBuffer(geometryState.positionsBuf,geometryState.compressGeometry?gl.UNSIGNED_SHORT:gl.FLOAT);frame.bindArray++;}if(geometryState.indicesBuf){geometryState.indicesBuf.bind();frame.bindArray++;}}this._lastGeometryId=geometryState.id;}if(geometryState.combineGeometry){if(geometryState.indicesBufCombined){gl.drawElements(geometryState.primitive,geometryState.indicesBufCombined.numItems,geometryState.indicesBufCombined.itemType,0);frame.drawElements++;}}else{if(geometryState.indicesBuf){gl.drawElements(geometryState.primitive,geometryState.indicesBuf.numItems,geometryState.indicesBuf.itemType,0);frame.drawElements++;}else if(geometryState.positions){gl.drawArrays(gl.TRIANGLES,0,geometryState.positions.numItems);frame.drawArrays++;}}};ShadowRenderer.prototype._allocate=function(mesh){var scene=mesh.scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._shaderSource);this._scene=scene;this._useCount=0;if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uPositionsDecodeMatrix=program.getLocation("positionsDecodeMatrix");this._uModelMatrix=program.getLocation("modelMatrix");this._uShadowViewMatrix=program.getLocation("shadowViewMatrix");this._uShadowProjMatrix=program.getLocation("shadowProjMatrix");this._uSectionPlanes={};var clips=scene._sectionPlanesState.sectionPlanes;for(var _i120=0,len=clips.length;_i1200){var sectionPlaneUniforms;var uSectionPlaneActive;var sectionPlane;var uSectionPlanePos;var uSectionPlaneDir;for(var _i121=0,len=this._uSectionPlanes.length;_i1210){var sectionPlaneUniforms;var uSectionPlaneActive;var sectionPlane;var uSectionPlanePos;var uSectionPlaneDir;for(var _i123=0,len=this._uSectionPlanes.length;_i1231&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Mesh);_this57=_super36.call(this,owner,cfg);/** + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this mESH. This is used to control the order in which + * mESHES are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. + */function Mesh(owner){var _this57;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Mesh);_this57=_super36.call(this,owner,cfg);_this57.renderOrder=cfg.renderOrder||0;/** * ID of the corresponding object within the originating system, if any. * * @type {String} @@ -11085,7 +11088,7 @@ value=value||0;value=Math.round(value);if(value===this._state.layer){return;}thi * Called by xeokit to compile shaders for this Mesh. * @private */},{key:"compile",value:function compile(){var drawHash=this._makeDrawHash();if(this._state.drawHash!==drawHash){this._state.drawHash=drawHash;this._putDrawRenderers();this._drawRenderer=DrawRenderer.get(this);// this._shadowRenderer = ShadowRenderer.get(this); -this._emphasisFillRenderer=EmphasisFillRenderer.get(this);this._emphasisEdgesRenderer=EmphasisEdgesRenderer.get(this);}var pickHash=this._makePickHash();if(this._state.pickHash!==pickHash){this._state.pickHash=pickHash;this._putPickRenderers();this._pickMeshRenderer=PickMeshRenderer.get(this);}if(this._state.occluder){var occlusionHash=this._makeOcclusionHash();if(this._state.occlusionHash!==occlusionHash){this._state.occlusionHash=occlusionHash;this._putOcclusionRenderer();this._occlusionRenderer=OcclusionRenderer.get(this);}}}},{key:"_setLocalMatrixDirty",value:function _setLocalMatrixDirty(){this._localMatrixDirty=true;this._setWorldMatrixDirty();}},{key:"_setWorldMatrixDirty",value:function _setWorldMatrixDirty(){this._worldMatrixDirty=true;this._worldNormalMatrixDirty=true;}},{key:"_buildWorldMatrix",value:function _buildWorldMatrix(){var localMatrix=this.matrix;if(!this._parentNode){for(var _i122=0,len=localMatrix.length;_i1220){for(var _i123=0;_i1230){for(var _i125=0;_i125-1){var geometry=mesh.geometry._state;var scene=mesh.scene;var camera=scene.camera;var _canvas2=scene.canvas;if(geometry.primitiveName==="triangles"){// Triangle picked; this only happens when the // Mesh has a Geometry that has primitives of type "triangle" pickResult.primitive="triangle";// Get the World-space positions of the triangle's vertices -var _i124=primIndex;// Indicates the first triangle index in the indices array +var _i126=primIndex;// Indicates the first triangle index in the indices array var indices=geometry.indices;// Indices into geometry arrays, not into shared VertexBufs -var positions=geometry.positions;var ia3;var ib3;var ic3;if(indices){var ia=indices[_i124+0];var ib=indices[_i124+1];var ic=indices[_i124+2];triangleVertices[0]=ia;triangleVertices[1]=ib;triangleVertices[2]=ic;pickResult.indices=triangleVertices;ia3=ia*3;ib3=ib*3;ic3=ic*3;}else{ia3=_i124*3;ib3=ia3+3;ic3=ib3+3;}positionA[0]=positions[ia3+0];positionA[1]=positions[ia3+1];positionA[2]=positions[ia3+2];positionB[0]=positions[ib3+0];positionB[1]=positions[ib3+1];positionB[2]=positions[ib3+2];positionC[0]=positions[ic3+0];positionC[1]=positions[ic3+1];positionC[2]=positions[ic3+2];if(geometry.compressGeometry){// Decompress vertex positions +var positions=geometry.positions;var ia3;var ib3;var ic3;if(indices){var ia=indices[_i126+0];var ib=indices[_i126+1];var ic=indices[_i126+2];triangleVertices[0]=ia;triangleVertices[1]=ib;triangleVertices[2]=ic;pickResult.indices=triangleVertices;ia3=ia*3;ib3=ib*3;ic3=ic*3;}else{ia3=_i126*3;ib3=ia3+3;ic3=ib3+3;}positionA[0]=positions[ia3+0];positionA[1]=positions[ia3+1];positionA[2]=positions[ia3+2];positionB[0]=positions[ib3+0];positionB[1]=positions[ib3+1];positionB[2]=positions[ib3+2];positionC[0]=positions[ic3+0];positionC[1]=positions[ic3+1];positionC[2]=positions[ic3+2];if(geometry.compressGeometry){// Decompress vertex positions var positionsDecodeMatrix=geometry.positionsDecodeMatrix;if(positionsDecodeMatrix){geometryCompressionUtils.decompressPosition(positionA,positionsDecodeMatrix,positionA);geometryCompressionUtils.decompressPosition(positionB,positionsDecodeMatrix,positionB);geometryCompressionUtils.decompressPosition(positionC,positionsDecodeMatrix,positionC);}}// Attempt to ray-pick the triangle in local space if(pickResult.canvasPos){math.canvasPosToLocalRay(_canvas2.canvas,mesh.origin?createRTCViewMat(pickViewMatrix,mesh.origin):pickViewMatrix,pickProjMatrix,mesh.worldMatrix,pickResult.canvasPos,localRayOrigin,localRayDir);}else if(pickResult.origin&&pickResult.direction){math.worldRayToLocalRay(mesh.worldMatrix,pickResult.origin,pickResult.direction,localRayOrigin,localRayDir);}math.normalizeVec3(localRayDir);math.rayPlaneIntersect(localRayOrigin,localRayDir,positionA,positionB,positionC,position);// Get Local-space cartesian coordinates of the ray-triangle intersection pickResult.localPos=position;pickResult.position=position;// Get interpolated World-space coordinates @@ -11399,7 +11402,7 @@ geometry:arrowShaft,material:zAxisMaterial,pickable:false,collidable:false,visib geometry:new ReadableGeometry(axisGizmoScene,buildVectorTextGeometry({text:"Z",size:1.5})),material:zAxisLabelMaterial,pickable:false,collidable:false,visible:cfg.visible!==false,position:[0,0,7],billboard:"spherical"})];return _this58;}/** Shows or hides this AxisGizmoPlugin. * * @param visible - */_createClass(AxisGizmoPlugin,[{key:"setVisible",value:function setVisible(visible){for(var _i125=0;_i1251&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,Node$2);_this60=_super39.call(this,owner,cfg);_this60._parentNode=null;_this60._children=[];_this60._aabb=null;_this60._aabbDirty=true;_this60.scene._aabbDirty=true;_this60._numTriangles=0;_this60._scale=math.vec3();_this60._quaternion=math.identityQuaternion();_this60._rotation=math.vec3();_this60._position=math.vec3();_this60._offset=math.vec3();_this60._localMatrix=math.identityMat4();_this60._worldMatrix=math.identityMat4();_this60._localMatrixDirty=true;_this60._worldMatrixDirty=true;if(cfg.matrix){_this60.matrix=cfg.matrix;}else{_this60.scale=cfg.scale;_this60.position=cfg.position;if(cfg.quaternion);else{_this60.rotation=cfg.rotation;}}_this60._isModel=cfg.isModel;if(_this60._isModel){_this60.scene._registerModel(_assertThisInitialized(_this60));}_this60._isObject=cfg.isObject;if(_this60._isObject){_this60.scene._registerObject(_assertThisInitialized(_this60));}_this60.origin=cfg.origin;_this60.visible=cfg.visible;_this60.culled=cfg.culled;_this60.pickable=cfg.pickable;_this60.clippable=cfg.clippable;_this60.collidable=cfg.collidable;_this60.castsShadow=cfg.castsShadow;_this60.receivesShadow=cfg.receivesShadow;_this60.xrayed=cfg.xrayed;_this60.highlighted=cfg.highlighted;_this60.selected=cfg.selected;_this60.edges=cfg.edges;_this60.colorize=cfg.colorize;_this60.opacity=cfg.opacity;_this60.offset=cfg.offset;// Add children, which inherit state from this Node -if(cfg.children){var children=cfg.children;for(var _i126=0,len=children.length;_i126Lambertian flat shading model for calculating reflectance. * * * Useful for efficiently rendering non-realistic objects for high-detail CAD. @@ -13123,11 +13126,11 @@ if(p===UnsignedInt248Type){return gl.UNSIGNED_INT_24_8;}if(p===RepeatWrapping){r * * @private */var Texture2D=/*#__PURE__*/function(){function Texture2D(_ref4){var gl=_ref4.gl,target=_ref4.target,format=_ref4.format,type=_ref4.type,wrapS=_ref4.wrapS,wrapT=_ref4.wrapT,wrapR=_ref4.wrapR,encoding=_ref4.encoding,preloadColor=_ref4.preloadColor,premultiplyAlpha=_ref4.premultiplyAlpha,flipY=_ref4.flipY;_classCallCheck(this,Texture2D);this.gl=gl;this.target=target||gl.TEXTURE_2D;this.format=format||RGBAFormat;this.type=type||UnsignedByteType;this.internalFormat=null;this.premultiplyAlpha=!!premultiplyAlpha;this.flipY=!!flipY;this.unpackAlignment=4;this.wrapS=wrapS||RepeatWrapping;this.wrapT=wrapT||RepeatWrapping;this.wrapR=wrapR||RepeatWrapping;this.encoding=encoding||sRGBEncoding;this.texture=gl.createTexture();if(preloadColor){this.setPreloadColor(preloadColor);// Prevents "there is no texture bound to the unit 0" error -}this.allocated=true;}_createClass(Texture2D,[{key:"setPreloadColor",value:function setPreloadColor(value){if(!value){color$4[0]=0;color$4[1]=0;color$4[2]=0;color$4[3]=255;}else{color$4[0]=Math.floor(value[0]*255);color$4[1]=Math.floor(value[1]*255);color$4[2]=Math.floor(value[2]*255);color$4[3]=Math.floor((value[3]!==undefined?value[3]:1)*255);}var gl=this.gl;gl.bindTexture(this.target,this.texture);if(this.target===gl.TEXTURE_CUBE_MAP){var faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(var _i149=0,len=faces.length;_i1491&&arguments[1]!==undefined?arguments[1]:{};var gl=this.gl;if(props.format!==undefined){this.format=props.format;}if(props.internalFormat!==undefined){this.internalFormat=props.internalFormat;}if(props.encoding!==undefined){this.encoding=props.encoding;}if(props.type!==undefined){this.type=props.type;}if(props.flipY!==undefined){this.flipY=props.flipY;}if(props.premultiplyAlpha!==undefined){this.premultiplyAlpha=props.premultiplyAlpha;}if(props.unpackAlignment!==undefined){this.unpackAlignment=props.unpackAlignment;}if(props.minFilter!==undefined){this.minFilter=props.minFilter;}if(props.magFilter!==undefined){this.magFilter=props.magFilter;}if(props.wrapS!==undefined){this.wrapS=props.wrapS;}if(props.wrapT!==undefined){this.wrapT=props.wrapT;}if(props.wrapR!==undefined){this.wrapR=props.wrapR;}var generateMipMap=false;gl.bindTexture(this.target,this.texture);var bak1=gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,this.flipY);var bak2=gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var bak3=gl.getParameter(gl.UNPACK_ALIGNMENT);gl.pixelStorei(gl.UNPACK_ALIGNMENT,this.unpackAlignment);var bak4=gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL);gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,gl.NONE);var minFilter=convertConstant(gl,this.minFilter);gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,minFilter);if(minFilter===gl.NEAREST_MIPMAP_NEAREST||minFilter===gl.LINEAR_MIPMAP_NEAREST||minFilter===gl.NEAREST_MIPMAP_LINEAR||minFilter===gl.LINEAR_MIPMAP_LINEAR){generateMipMap=true;}var magFilter=convertConstant(gl,this.magFilter);if(magFilter){gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,magFilter);}var wrapS=convertConstant(gl,this.wrapS);if(wrapS){gl.texParameteri(this.target,gl.TEXTURE_WRAP_S,wrapS);}var wrapT=convertConstant(gl,this.wrapT);if(wrapT){gl.texParameteri(this.target,gl.TEXTURE_WRAP_T,wrapT);}var glFormat=convertConstant(gl,this.format,this.encoding);var glType=convertConstant(gl,this.type);var glInternalFormat=getInternalFormat(gl,this.internalFormat,glFormat,glType,this.encoding,false);if(this.target===gl.TEXTURE_CUBE_MAP){if(utils.isArray(image)){var images=image;var faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(var _i150=0,len=faces.length;_i1501;gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,this.flipY);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);gl.pixelStorei(gl.UNPACK_ALIGNMENT,this.unpackAlignment);gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,gl.NONE);var wrapS=convertConstant(gl,this.wrapS);if(wrapS){gl.texParameteri(this.target,gl.TEXTURE_WRAP_S,wrapS);}var wrapT=convertConstant(gl,this.wrapT);if(wrapT){gl.texParameteri(this.target,gl.TEXTURE_WRAP_T,wrapT);}if(this.type===gl.TEXTURE_3D||this.type===gl.TEXTURE_2D_ARRAY){var wrapR=convertConstant(gl,this.wrapR);if(wrapR){gl.texParameteri(this.target,gl.TEXTURE_WRAP_R,wrapR);}gl.texParameteri(this.type,gl.TEXTURE_WRAP_R,wrapR);}if(supportsMips){gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,filterFallback(gl,this.minFilter));gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,filterFallback(gl,this.magFilter));}else{gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,convertConstant(gl,this.minFilter));gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,convertConstant(gl,this.magFilter));}var glFormat=convertConstant(gl,this.format,this.encoding);var glType=convertConstant(gl,this.type);var glInternalFormat=getInternalFormat(gl,this.internalFormat,glFormat,glType,this.encoding,false);gl.texStorage2D(gl.TEXTURE_2D,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height);for(var _i151=0,len=mipmaps.length;_i1511&&arguments[1]!==undefined?arguments[1]:{};var gl=this.gl;if(props.format!==undefined){this.format=props.format;}if(props.internalFormat!==undefined){this.internalFormat=props.internalFormat;}if(props.encoding!==undefined){this.encoding=props.encoding;}if(props.type!==undefined){this.type=props.type;}if(props.flipY!==undefined){this.flipY=props.flipY;}if(props.premultiplyAlpha!==undefined){this.premultiplyAlpha=props.premultiplyAlpha;}if(props.unpackAlignment!==undefined){this.unpackAlignment=props.unpackAlignment;}if(props.minFilter!==undefined){this.minFilter=props.minFilter;}if(props.magFilter!==undefined){this.magFilter=props.magFilter;}if(props.wrapS!==undefined){this.wrapS=props.wrapS;}if(props.wrapT!==undefined){this.wrapT=props.wrapT;}if(props.wrapR!==undefined){this.wrapR=props.wrapR;}var generateMipMap=false;gl.bindTexture(this.target,this.texture);var bak1=gl.getParameter(gl.UNPACK_FLIP_Y_WEBGL);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,this.flipY);var bak2=gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var bak3=gl.getParameter(gl.UNPACK_ALIGNMENT);gl.pixelStorei(gl.UNPACK_ALIGNMENT,this.unpackAlignment);var bak4=gl.getParameter(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL);gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,gl.NONE);var minFilter=convertConstant(gl,this.minFilter);gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,minFilter);if(minFilter===gl.NEAREST_MIPMAP_NEAREST||minFilter===gl.LINEAR_MIPMAP_NEAREST||minFilter===gl.NEAREST_MIPMAP_LINEAR||minFilter===gl.LINEAR_MIPMAP_LINEAR){generateMipMap=true;}var magFilter=convertConstant(gl,this.magFilter);if(magFilter){gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,magFilter);}var wrapS=convertConstant(gl,this.wrapS);if(wrapS){gl.texParameteri(this.target,gl.TEXTURE_WRAP_S,wrapS);}var wrapT=convertConstant(gl,this.wrapT);if(wrapT){gl.texParameteri(this.target,gl.TEXTURE_WRAP_T,wrapT);}var glFormat=convertConstant(gl,this.format,this.encoding);var glType=convertConstant(gl,this.type);var glInternalFormat=getInternalFormat(gl,this.internalFormat,glFormat,glType,this.encoding,false);if(this.target===gl.TEXTURE_CUBE_MAP){if(utils.isArray(image)){var images=image;var faces=[gl.TEXTURE_CUBE_MAP_POSITIVE_X,gl.TEXTURE_CUBE_MAP_NEGATIVE_X,gl.TEXTURE_CUBE_MAP_POSITIVE_Y,gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,gl.TEXTURE_CUBE_MAP_POSITIVE_Z,gl.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(var _i152=0,len=faces.length;_i1521;gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,this.flipY);gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);gl.pixelStorei(gl.UNPACK_ALIGNMENT,this.unpackAlignment);gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,gl.NONE);var wrapS=convertConstant(gl,this.wrapS);if(wrapS){gl.texParameteri(this.target,gl.TEXTURE_WRAP_S,wrapS);}var wrapT=convertConstant(gl,this.wrapT);if(wrapT){gl.texParameteri(this.target,gl.TEXTURE_WRAP_T,wrapT);}if(this.type===gl.TEXTURE_3D||this.type===gl.TEXTURE_2D_ARRAY){var wrapR=convertConstant(gl,this.wrapR);if(wrapR){gl.texParameteri(this.target,gl.TEXTURE_WRAP_R,wrapR);}gl.texParameteri(this.type,gl.TEXTURE_WRAP_R,wrapR);}if(supportsMips){gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,filterFallback(gl,this.minFilter));gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,filterFallback(gl,this.magFilter));}else{gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,convertConstant(gl,this.minFilter));gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,convertConstant(gl,this.magFilter));}var glFormat=convertConstant(gl,this.format,this.encoding);var glType=convertConstant(gl,this.type);var glInternalFormat=getInternalFormat(gl,this.internalFormat,glFormat,glType,this.encoding,false);gl.texStorage2D(gl.TEXTURE_2D,levels,glInternalFormat,mipmaps[0].width,mipmaps[0].height);for(var _i153=0,len=mipmaps.length;_i1535&&arguments[5]!==undefined?arguments[5]:false;if(internalFormatName!==null){if(gl[internalFormatName]!==undefined){return gl[internalFormatName];}console.warn('Attempt to use non-existing WebGL internal format \''+internalFormatName+'\'');}var internalFormat=glFormat;if(glFormat===gl.RED){if(glType===gl.FLOAT)internalFormat=gl.R32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.R16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=gl.R8;}if(glFormat===gl.RG){if(glType===gl.FLOAT)internalFormat=gl.RG32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.RG16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=gl.RG8;}if(glFormat===gl.RGBA){if(glType===gl.FLOAT)internalFormat=gl.RGBA32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.RGBA16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=encoding===sRGBEncoding&&isVideoTexture===false?gl.SRGB8_ALPHA8:gl.RGBA8;if(glType===gl.UNSIGNED_SHORT_4_4_4_4)internalFormat=gl.RGBA4;if(glType===gl.UNSIGNED_SHORT_5_5_5_1)internalFormat=gl.RGB5_A1;}if(internalFormat===gl.R16F||internalFormat===gl.R32F||internalFormat===gl.RG16F||internalFormat===gl.RG32F||internalFormat===gl.RGBA16F||internalFormat===gl.RGBA32F){getExtension(gl,'EXT_color_buffer_float');}return internalFormat;}function filterFallback(gl,f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return gl.NEAREST;}return gl.LINEAR;}function ensureImageSizePowerOfTwo$1(image){if(!isPowerOfTwo$1(image.width)||!isPowerOfTwo$1(image.height)){var _canvas3=document.createElement("canvas");_canvas3.width=nextHighestPowerOfTwo$1(image.width);_canvas3.height=nextHighestPowerOfTwo$1(image.height);var ctx=_canvas3.getContext("2d");ctx.drawImage(image,0,0,image.width,image.height,0,0,_canvas3.width,_canvas3.height);image=_canvas3;}return image;}function isPowerOfTwo$1(x){return(x&x-1)===0;}function nextHighestPowerOfTwo$1(x){--x;for(var _i152=1;_i152<32;_i152<<=1){x=x|x>>_i152;}return x+1;}/** +gl.bindTexture(this.target,null);}},{key:"setProps",value:function setProps(props){var gl=this.gl;gl.bindTexture(this.target,this.texture);this._uploadProps(props);gl.bindTexture(this.target,null);}},{key:"_uploadProps",value:function _uploadProps(props){var gl=this.gl;if(props.format!==undefined){this.format=props.format;}if(props.internalFormat!==undefined){this.internalFormat=props.internalFormat;}if(props.encoding!==undefined){this.encoding=props.encoding;}if(props.type!==undefined){this.type=props.type;}if(props.minFilter!==undefined){var minFilter=convertConstant(gl,props.minFilter);if(minFilter){this.minFilter=props.minFilter;gl.texParameteri(this.target,gl.TEXTURE_MIN_FILTER,minFilter);if(minFilter===gl.NEAREST_MIPMAP_NEAREST||minFilter===gl.LINEAR_MIPMAP_NEAREST||minFilter===gl.NEAREST_MIPMAP_LINEAR||minFilter===gl.LINEAR_MIPMAP_LINEAR){gl.generateMipmap(this.target);}}}if(props.magFilter!==undefined){var magFilter=convertConstant(gl,props.magFilter);if(magFilter){this.magFilter=props.magFilter;gl.texParameteri(this.target,gl.TEXTURE_MAG_FILTER,magFilter);}}if(props.wrapS!==undefined){var wrapS=convertConstant(gl,props.wrapS);if(wrapS){this.wrapS=props.wrapS;gl.texParameteri(this.target,gl.TEXTURE_WRAP_S,wrapS);}}if(props.wrapT!==undefined){var wrapT=convertConstant(gl,props.wrapT);if(wrapT){this.wrapT=props.wrapT;gl.texParameteri(this.target,gl.TEXTURE_WRAP_T,wrapT);}}}},{key:"bind",value:function bind(unit){if(!this.allocated){return;}if(this.texture){var _gl2=this.gl;_gl2.activeTexture(_gl2["TEXTURE"+unit]);_gl2.bindTexture(this.target,this.texture);return true;}return false;}},{key:"unbind",value:function unbind(unit){if(!this.allocated){return;}if(this.texture){var _gl3=this.gl;_gl3.activeTexture(_gl3["TEXTURE"+unit]);_gl3.bindTexture(this.target,null);}}},{key:"destroy",value:function destroy(){if(!this.allocated){return;}if(this.texture){this.gl.deleteTexture(this.texture);this.texture=null;}}}]);return Texture2D;}();function getInternalFormat(gl,internalFormatName,glFormat,glType,encoding){var isVideoTexture=arguments.length>5&&arguments[5]!==undefined?arguments[5]:false;if(internalFormatName!==null){if(gl[internalFormatName]!==undefined){return gl[internalFormatName];}console.warn('Attempt to use non-existing WebGL internal format \''+internalFormatName+'\'');}var internalFormat=glFormat;if(glFormat===gl.RED){if(glType===gl.FLOAT)internalFormat=gl.R32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.R16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=gl.R8;}if(glFormat===gl.RG){if(glType===gl.FLOAT)internalFormat=gl.RG32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.RG16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=gl.RG8;}if(glFormat===gl.RGBA){if(glType===gl.FLOAT)internalFormat=gl.RGBA32F;if(glType===gl.HALF_FLOAT)internalFormat=gl.RGBA16F;if(glType===gl.UNSIGNED_BYTE)internalFormat=encoding===sRGBEncoding&&isVideoTexture===false?gl.SRGB8_ALPHA8:gl.RGBA8;if(glType===gl.UNSIGNED_SHORT_4_4_4_4)internalFormat=gl.RGBA4;if(glType===gl.UNSIGNED_SHORT_5_5_5_1)internalFormat=gl.RGB5_A1;}if(internalFormat===gl.R16F||internalFormat===gl.R32F||internalFormat===gl.RG16F||internalFormat===gl.RG32F||internalFormat===gl.RGBA16F||internalFormat===gl.RGBA32F){getExtension(gl,'EXT_color_buffer_float');}return internalFormat;}function filterFallback(gl,f){if(f===NearestFilter||f===NearestMipmapNearestFilter||f===NearestMipmapLinearFilter){return gl.NEAREST;}return gl.LINEAR;}function ensureImageSizePowerOfTwo$1(image){if(!isPowerOfTwo$1(image.width)||!isPowerOfTwo$1(image.height)){var _canvas3=document.createElement("canvas");_canvas3.width=nextHighestPowerOfTwo$1(image.width);_canvas3.height=nextHighestPowerOfTwo$1(image.height);var ctx=_canvas3.getContext("2d");ctx.drawImage(image,0,0,image.width,image.height,0,0,_canvas3.width,_canvas3.height);image=_canvas3;}return image;}function isPowerOfTwo$1(x){return(x&x-1)===0;}function nextHighestPowerOfTwo$1(x){--x;for(var _i154=1;_i154<32;_i154<<=1){x=x|x>>_i154;}return x+1;}/** * @desc A 2D texture map. * * * Textures are attached to {@link Material}s, which are attached to {@link Mesh}es. @@ -13941,7 +13944,7 @@ var positions=K3D.edit.unwrap(m.i_verts,m.c_verts,3);var normals=K3D.edit.unwrap * @param {Number} [cfg.size=1] Dimension on the X and Z-axis. * @param {Number} [cfg.divisions=1] Number of divisions on X and Z axis.. * @returns {Object} Configuration for a {@link Geometry} subtype. - */function buildGridGeometry(){var cfg=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var size=cfg.size||1;if(size<0){console.error("negative size not allowed - will invert");size*=-1;}var divisions=cfg.divisions||1;if(divisions<0){console.error("negative divisions not allowed - will invert");divisions*=-1;}if(divisions<1){divisions=1;}size=size||10;divisions=divisions||10;var step=size/divisions;var halfSize=size/2;var positions=[];var indices=[];var l=0;for(var _i153=0,k=-halfSize;_i153<=divisions;_i153++,k+=step){positions.push(-halfSize);positions.push(0);positions.push(k);positions.push(halfSize);positions.push(0);positions.push(k);positions.push(k);positions.push(0);positions.push(-halfSize);positions.push(k);positions.push(0);positions.push(halfSize);indices.push(l++);indices.push(l++);indices.push(l++);indices.push(l++);}return utils.apply(cfg,{primitive:"lines",positions:positions,indices:indices});}/** + */function buildGridGeometry(){var cfg=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var size=cfg.size||1;if(size<0){console.error("negative size not allowed - will invert");size*=-1;}var divisions=cfg.divisions||1;if(divisions<0){console.error("negative divisions not allowed - will invert");divisions*=-1;}if(divisions<1){divisions=1;}size=size||10;divisions=divisions||10;var step=size/divisions;var halfSize=size/2;var positions=[];var indices=[];var l=0;for(var _i155=0,k=-halfSize;_i155<=divisions;_i155++,k+=step){positions.push(-halfSize);positions.push(0);positions.push(k);positions.push(halfSize);positions.push(0);positions.push(k);positions.push(k);positions.push(0);positions.push(-halfSize);positions.push(k);positions.push(0);positions.push(halfSize);indices.push(l++);indices.push(l++);indices.push(l++);indices.push(l++);}return utils.apply(cfg,{primitive:"lines",positions:positions,indices:indices});}/** * @desc Creates a plane-shaped {@link Geometry}. * * ## Usage @@ -14093,7 +14096,7 @@ var positions=K3D.edit.unwrap(m.i_verts,m.c_verts,3);var normals=K3D.edit.unwrap * @param {String} [cfg.id] Optional ID, unique among all components in the parent {@link Scene}, generated automatically when omitted. * @param {Number[]} [cfg.points] 3D points indicating vertices position. * @returns {Object} Configuration for a {@link Geometry} subtype. - */function buildPolylineGeometry(){var cfg=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(cfg.points.length%3!==0){throw"Size of points array for given polyline should be divisible by 3";}var numberOfPoints=cfg.points.length/3;if(numberOfPoints<2){throw"There should be at least 2 points to create a polyline";}var indices=[];for(var _i154=0;_i1540&&arguments[0]!==undefined?arguments[0]:{};if(cfg.points.length%3!==0){throw"Size of points array for given polyline should be divisible by 3";}var numberOfPoints=cfg.points.length/3;if(numberOfPoints<2){throw"There should be at least 2 points to create a polyline";}var indices=[];for(var _i156=0;_i1561&&arguments[1]!==undefined?arguments[1]:false;src.push("uniform Matrices {");src.push(" mat4 worldMatrix;");src.push(" mat4 viewMatrix;");src.push(" mat4 projMatrix;");src.push(" mat4 positionsDecodeMatrix;");if(normals){src.push(" mat4 worldNormalMatrix;");src.push(" mat4 viewNormalMatrix;");}src.push("};");return src;}},{key:"_addRemapClipPosLines",value:function _addRemapClipPosLines(src){var viewportSize=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;src.push("uniform vec2 drawingBufferSize;");src.push("uniform vec2 pickClipPos;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");if(viewportSize===1){src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");}else{src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(viewportSize,"));"));}src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");return src;}},{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"setSectionPlanesStateUniforms",value:function setSectionPlanesStateUniforms(layer){var scene=this._scene;var gl=scene.canvas.gl;var model=layer.model,layerIndex=layer.layerIndex;var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;if(scene.crossSections){gl.uniform4fv(this._uSliceColor,scene.crossSections.sliceColor);gl.uniform1f(this._uSliceThickness,scene.crossSections.sliceThickness);}for(var sectionPlaneIndex=0;sectionPlaneIndex0){this._uReflectionMap="reflectionMap";}if(lightsState.lightMaps.length>0){this._uLightMap="lightMap";}this._uSectionPlanes=[];for(var _i156=0,_len19=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i156<_len19;_i156++){this._uSectionPlanes.push({active:program.getLocation("sectionPlaneActive"+_i156),pos:program.getLocation("sectionPlanePos"+_i156),dir:program.getLocation("sectionPlaneDir"+_i156)});}this._aPosition=program.getAttribute("position");this._aOffset=program.getAttribute("offset");this._aNormal=program.getAttribute("normal");this._aUV=program.getAttribute("uv");this._aColor=program.getAttribute("color");this._aMetallicRoughness=program.getAttribute("metallicRoughness");this._aFlags=program.getAttribute("flags");this._aPickColor=program.getAttribute("pickColor");this._uPickZNear=program.getLocation("pickZNear");this._uPickZFar=program.getLocation("pickZFar");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uColorMap="uColorMap";this._uMetallicRoughMap="uMetallicRoughMap";this._uEmissiveMap="uEmissiveMap";this._uNormalMap="uNormalMap";this._uAOMap="uAOMap";if(this._instancing){this._aModelMatrix=program.getAttribute("modelMatrix");this._aModelMatrixCol0=program.getAttribute("modelMatrixCol0");this._aModelMatrixCol1=program.getAttribute("modelMatrixCol1");this._aModelMatrixCol2=program.getAttribute("modelMatrixCol2");this._aModelNormalMatrixCol0=program.getAttribute("modelNormalMatrixCol0");this._aModelNormalMatrixCol1=program.getAttribute("modelNormalMatrixCol1");this._aModelNormalMatrixCol2=program.getAttribute("modelNormalMatrixCol2");}if(this._withSAO){this._uOcclusionTexture="uOcclusionTexture";this._uSAOParams=program.getLocation("uSAOParams");}if(scene.logarithmicDepthBufferEnabled){this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}if(scene.pointsMaterial._state.filterIntensity){this._uIntensityRange=program.getLocation("intensityRange");}this._uPointSize=program.getLocation("pointSize");this._uNearPlaneHeight=program.getLocation("nearPlaneHeight");if(scene.crossSections){this._uSliceColor=program.getLocation("sliceColor");this._uSliceThickness=program.getLocation("sliceThickness");}}},{key:"_bindProgram",value:function _bindProgram(frameCtx){var scene=this._scene;var gl=scene.canvas.gl;var program=this._program;var lightsState=scene._lightsState;var lights=lightsState.lights;program.bind();frameCtx.textureUnit=0;if(this._uLightAmbient){gl.uniform4fv(this._uLightAmbient,lightsState.getAmbientColorAndIntensity());}if(this._uGammaFactor){gl.uniform1f(this._uGammaFactor,scene.gammaFactor);}for(var _i157=0,len=lights.length;_i1573&&arguments[3]!==undefined?arguments[3]:{},_ref7$colorUniform=_ref7.colorUniform,colorUniform=_ref7$colorUniform===void 0?false:_ref7$colorUniform,_ref7$incrementDrawSt=_ref7.incrementDrawState,incrementDrawState=_ref7$incrementDrawSt===void 0?false:_ref7$incrementDrawSt;var maxTextureUnits=WEBGL_INFO.MAX_TEXTURE_IMAGE_UNITS;var scene=this._scene;var gl=scene.canvas.gl;var state=layer._state,model=layer.model;var textureSet=state.textureSet,origin=state.origin,positionsDecodeMatrix=state.positionsDecodeMatrix;var lightsState=scene._lightsState;var pointsMaterial=scene.pointsMaterial;var camera=model.scene.camera;var viewNormalMatrix=camera.viewNormalMatrix,project=camera.project;var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate,worldNormalMatrix=model.worldNormalMatrix;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx);}if(this._vaoCache.has(layer)){gl.bindVertexArray(this._vaoCache.get(layer));}else{this._vaoCache.set(layer,this._makeVAO(state));}var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$C;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$t);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];this._matricesUniformBlockBufferData.set(createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$r),offset+=mat4Size);}else{this._matricesUniformBlockBufferData.set(viewMatrix,offset+=mat4Size);}this._matricesUniformBlockBufferData.set(frameCtx.pickProjMatrix||project.matrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(positionsDecodeMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(worldNormalMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(viewNormalMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);gl.uniform1i(this._uRenderPass,renderPass);this.setSectionPlanesStateUniforms(layer);if(scene.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix? +var lights=lightsState.lights;var light;for(var _i157=0,len=lights.length;_i1570){this._uReflectionMap="reflectionMap";}if(lightsState.lightMaps.length>0){this._uLightMap="lightMap";}this._uSectionPlanes=[];for(var _i158=0,_len19=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i158<_len19;_i158++){this._uSectionPlanes.push({active:program.getLocation("sectionPlaneActive"+_i158),pos:program.getLocation("sectionPlanePos"+_i158),dir:program.getLocation("sectionPlaneDir"+_i158)});}this._aPosition=program.getAttribute("position");this._aOffset=program.getAttribute("offset");this._aNormal=program.getAttribute("normal");this._aUV=program.getAttribute("uv");this._aColor=program.getAttribute("color");this._aMetallicRoughness=program.getAttribute("metallicRoughness");this._aFlags=program.getAttribute("flags");this._aPickColor=program.getAttribute("pickColor");this._uPickZNear=program.getLocation("pickZNear");this._uPickZFar=program.getLocation("pickZFar");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uColorMap="uColorMap";this._uMetallicRoughMap="uMetallicRoughMap";this._uEmissiveMap="uEmissiveMap";this._uNormalMap="uNormalMap";this._uAOMap="uAOMap";if(this._instancing){this._aModelMatrix=program.getAttribute("modelMatrix");this._aModelMatrixCol0=program.getAttribute("modelMatrixCol0");this._aModelMatrixCol1=program.getAttribute("modelMatrixCol1");this._aModelMatrixCol2=program.getAttribute("modelMatrixCol2");this._aModelNormalMatrixCol0=program.getAttribute("modelNormalMatrixCol0");this._aModelNormalMatrixCol1=program.getAttribute("modelNormalMatrixCol1");this._aModelNormalMatrixCol2=program.getAttribute("modelNormalMatrixCol2");}if(this._withSAO){this._uOcclusionTexture="uOcclusionTexture";this._uSAOParams=program.getLocation("uSAOParams");}if(scene.logarithmicDepthBufferEnabled){this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}if(scene.pointsMaterial._state.filterIntensity){this._uIntensityRange=program.getLocation("intensityRange");}this._uPointSize=program.getLocation("pointSize");this._uNearPlaneHeight=program.getLocation("nearPlaneHeight");if(scene.crossSections){this._uSliceColor=program.getLocation("sliceColor");this._uSliceThickness=program.getLocation("sliceThickness");}}},{key:"_bindProgram",value:function _bindProgram(frameCtx){var scene=this._scene;var gl=scene.canvas.gl;var program=this._program;var lightsState=scene._lightsState;var lights=lightsState.lights;program.bind();frameCtx.textureUnit=0;if(this._uLightAmbient){gl.uniform4fv(this._uLightAmbient,lightsState.getAmbientColorAndIntensity());}if(this._uGammaFactor){gl.uniform1f(this._uGammaFactor,scene.gammaFactor);}for(var _i159=0,len=lights.length;_i1593&&arguments[3]!==undefined?arguments[3]:{},_ref7$colorUniform=_ref7.colorUniform,colorUniform=_ref7$colorUniform===void 0?false:_ref7$colorUniform,_ref7$incrementDrawSt=_ref7.incrementDrawState,incrementDrawState=_ref7$incrementDrawSt===void 0?false:_ref7$incrementDrawSt;var maxTextureUnits=WEBGL_INFO.MAX_TEXTURE_IMAGE_UNITS;var scene=this._scene;var gl=scene.canvas.gl;var state=layer._state,model=layer.model;var textureSet=state.textureSet,origin=state.origin,positionsDecodeMatrix=state.positionsDecodeMatrix;var lightsState=scene._lightsState;var pointsMaterial=scene.pointsMaterial;var camera=model.scene.camera;var viewNormalMatrix=camera.viewNormalMatrix,project=camera.project;var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate,worldNormalMatrix=model.worldNormalMatrix;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx);}if(this._vaoCache.has(layer)){gl.bindVertexArray(this._vaoCache.get(layer));}else{this._vaoCache.set(layer,this._makeVAO(state));}var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$C;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$t);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];this._matricesUniformBlockBufferData.set(createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$r),offset+=mat4Size);}else{this._matricesUniformBlockBufferData.set(viewMatrix,offset+=mat4Size);}this._matricesUniformBlockBufferData.set(frameCtx.pickProjMatrix||project.matrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(positionsDecodeMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(worldNormalMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(viewNormalMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);gl.uniform1i(this._uRenderPass,renderPass);this.setSectionPlanesStateUniforms(layer);if(scene.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix? gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}if(this._uZFar){gl.uniform1f(this._uZFar,scene.camera.project.far);}}if(this._uPickInvisible){gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);}if(this._uPickZNear){gl.uniform1f(this._uPickZNear,frameCtx.pickZNear);}if(this._uPickZFar){gl.uniform1f(this._uPickZFar,frameCtx.pickZFar);}if(this._uPickClipPos){gl.uniform2fv(this._uPickClipPos,frameCtx.pickClipPos);}if(this._uDrawingBufferSize){gl.uniform2f(this._uDrawingBufferSize,gl.drawingBufferWidth,gl.drawingBufferHeight);}if(this._uUVDecodeMatrix){gl.uniformMatrix3fv(this._uUVDecodeMatrix,false,state.uvDecodeMatrix);}if(this._uIntensityRange&&pointsMaterial.filterIntensity){gl.uniform2f(this._uIntensityRange,pointsMaterial.minIntensity,pointsMaterial.maxIntensity);}if(this._uPointSize){gl.uniform1f(this._uPointSize,pointsMaterial.pointSize);}if(this._uNearPlaneHeight){var nearPlaneHeight=scene.camera.projection==="ortho"?1.0:gl.drawingBufferHeight/(2*Math.tan(0.5*scene.camera.perspective.fov*Math.PI/180.0));gl.uniform1f(this._uNearPlaneHeight,nearPlaneHeight);}if(textureSet){var colorTexture=textureSet.colorTexture,metallicRoughnessTexture=textureSet.metallicRoughnessTexture,emissiveTexture=textureSet.emissiveTexture,normalsTexture=textureSet.normalsTexture,occlusionTexture=textureSet.occlusionTexture;if(this._uColorMap&&colorTexture){this._program.bindTexture(this._uColorMap,colorTexture.texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;}if(this._uMetallicRoughMap&&metallicRoughnessTexture){this._program.bindTexture(this._uMetallicRoughMap,metallicRoughnessTexture.texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;}if(this._uEmissiveMap&&emissiveTexture){this._program.bindTexture(this._uEmissiveMap,emissiveTexture.texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;}if(this._uNormalMap&&normalsTexture){this._program.bindTexture(this._uNormalMap,normalsTexture.texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;}if(this._uAOMap&&occlusionTexture){this._program.bindTexture(this._uAOMap,occlusionTexture.texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;}}if(lightsState.reflectionMaps.length>0&&lightsState.reflectionMaps[0].texture&&this._uReflectionMap){this._program.bindTexture(this._uReflectionMap,lightsState.reflectionMaps[0].texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;frameCtx.bindTexture++;}if(lightsState.lightMaps.length>0&&lightsState.lightMaps[0].texture&&this._uLightMap){this._program.bindTexture(this._uLightMap,lightsState.lightMaps[0].texture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;frameCtx.bindTexture++;}if(this._withSAO){var sao=scene.sao;var saoEnabled=sao.possible;if(saoEnabled){var viewportWidth=gl.drawingBufferWidth;var viewportHeight=gl.drawingBufferHeight;tempVec4[0]=viewportWidth;tempVec4[1]=viewportHeight;tempVec4[2]=sao.blendCutoff;tempVec4[3]=sao.blendFactor;gl.uniform4fv(this._uSAOParams,tempVec4);this._program.bindTexture(this._uOcclusionTexture,frameCtx.occlusionTexture,frameCtx.textureUnit);frameCtx.textureUnit=(frameCtx.textureUnit+1)%maxTextureUnits;frameCtx.bindTexture++;}}if(colorUniform){var colorKey=this._edges?"edgeColor":"fillColor";var alphaKey=this._edges?"edgeAlpha":"fillAlpha";if(renderPass===RENDER_PASSES["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var material=scene.xrayMaterial._state;var _color3=material[colorKey];var alpha=material[alphaKey];gl.uniform4f(this._uColor,_color3[0],_color3[1],_color3[2],alpha);}else if(renderPass===RENDER_PASSES["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var _material=scene.highlightMaterial._state;var _color4=_material[colorKey];var _alpha=_material[alphaKey];gl.uniform4f(this._uColor,_color4[0],_color4[1],_color4[2],_alpha);}else if(renderPass===RENDER_PASSES["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var _material2=scene.selectedMaterial._state;var _color5=_material2[colorKey];var _alpha2=_material2[alphaKey];gl.uniform4f(this._uColor,_color5[0],_color5[1],_color5[2],_alpha2);}else{gl.uniform4fv(this._uColor,this._edges?edgesDefaultColor:defaultColor$2);}}this._draw({state:state,frameCtx:frameCtx,incrementDrawState:incrementDrawState});gl.bindVertexArray(null);}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;stats.memory.programs--;}}]);return VBORenderer;}();/** * @private */var TrianglesBatchingRenderer=/*#__PURE__*/function(_VBORenderer){_inherits(TrianglesBatchingRenderer,_VBORenderer);var _super47=_createSuper(TrianglesBatchingRenderer);function TrianglesBatchingRenderer(scene,withSAO){var _ref8=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{},_ref8$edges=_ref8.edges,edges=_ref8$edges===void 0?false:_ref8$edges;_classCallCheck(this,TrianglesBatchingRenderer);return _super47.call(this,scene,withSAO,{instancing:false,edges:edges});}_createClass(TrianglesBatchingRenderer,[{key:"_draw",value:function _draw(drawCfg){var gl=this._scene.canvas.gl;var state=drawCfg.state,frameCtx=drawCfg.frameCtx,incrementDrawState=drawCfg.incrementDrawState;if(this._edges){gl.drawElements(gl.LINES,state.edgeIndicesBuf.numItems,state.edgeIndicesBuf.itemType,0);}else{var count=frameCtx.pickElementsCount||state.indicesBuf.numItems;var offset=frameCtx.pickElementsOffset?frameCtx.pickElementsOffset*state.indicesBuf.itemByteSize:0;gl.drawElements(gl.TRIANGLES,count,state.indicesBuf.itemType,offset);if(incrementDrawState){frameCtx.drawElements++;}}}}]);return TrianglesBatchingRenderer;}(VBORenderer);/** * @private - */var TrianglesColorRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen){_inherits(TrianglesColorRenderer$1,_TrianglesBatchingRen);var _super48=_createSuper(TrianglesColorRenderer$1);function TrianglesColorRenderer$1(){_classCallCheck(this,TrianglesColorRenderer$1);return _super48.apply(this,arguments);}_createClass(TrianglesColorRenderer$1,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(TrianglesColorRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var light;var src=[];src.push("#version 300 es");src.push("// Triangles batching draw vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec3 normal;");src.push("in vec4 color;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}this._addMatricesUniformBlockLines(src,true);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("uniform vec4 lightAmbient;");for(var _i158=0,len=lightsState.lights.length;_i158= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT + */var TrianglesColorRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen){_inherits(TrianglesColorRenderer$1,_TrianglesBatchingRen);var _super48=_createSuper(TrianglesColorRenderer$1);function TrianglesColorRenderer$1(){_classCallCheck(this,TrianglesColorRenderer$1);return _super48.apply(this,arguments);}_createClass(TrianglesColorRenderer$1,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(TrianglesColorRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var light;var src=[];src.push("#version 300 es");src.push("// Triangles batching draw vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec3 normal;");src.push("in vec4 color;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}this._addMatricesUniformBlockLines(src,true);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("uniform vec4 lightAmbient;");for(var _i160=0,len=lightsState.lights.length;_i160= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(var _i159=0,_len20=lightsState.lights.length;_i159<_len20;_i159++){light=lightsState.lights[_i159];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i159+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i159+", 0.0)).xyz);");}}else if(light.type==="point"){if(light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i159+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i159+", 0.0)).xyz);");}}else if(light.type==="spot"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i159+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i159+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i159+".rgb * lightColor"+_i159+".a);");}src.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));");src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i160=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i160> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i161=0,_len21=sectionPlanesState.getNumAllocatedSectionPlanes();_i161<_len21;_i161++){src.push("if (sectionPlaneActive"+_i161+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i161+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i161+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top +src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(var _i161=0,_len20=lightsState.lights.length;_i161<_len20;_i161++){light=lightsState.lights[_i161];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i161+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i161+", 0.0)).xyz);");}}else if(light.type==="point"){if(light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i161+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i161+", 0.0)).xyz);");}}else if(light.type==="spot"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i161+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i161+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i161+".rgb * lightColor"+_i161+".a);");}src.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));");src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i162=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i162> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i163=0,_len21=sectionPlanesState.getNumAllocatedSectionPlanes();_i163<_len21;_i163++){src.push("if (sectionPlaneActive"+_i163+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i163+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i163+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewportHeight = uSAOParams[1];");src.push(" float blendCutoff = uSAOParams[2];");src.push(" float blendFactor = uSAOParams[3];");src.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);");src.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;");src.push(" outColor = vec4(newColor.rgb * ambient, 1.0);");}else{src.push(" outColor = newColor;");}src.push("}");return src;}}]);return TrianglesColorRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesFlatColorRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen2){_inherits(TrianglesFlatColorRenderer$1,_TrianglesBatchingRen2);var _super49=_createSuper(TrianglesFlatColorRenderer$1);function TrianglesFlatColorRenderer$1(){_classCallCheck(this,TrianglesFlatColorRenderer$1);return _super49.apply(this,arguments);}_createClass(TrianglesFlatColorRenderer$1,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching flat-shading draw vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vViewPosition = viewPosition;");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var lightsState=scene._lightsState;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching flat-shading draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i162=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i162> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i164=0,_len23=sectionPlanesState.getNumAllocatedSectionPlanes();_i164<_len23;_i164++){src.push("if (sectionPlaneActive"+_i164+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i164+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i164+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var _i165=0,_len24=lightsState.lights.length;_i165<_len24;_i165++){var _light4=lightsState.lights[_i165];if(_light4.type==="ambient"){continue;}if(_light4.type==="dir"){if(_light4.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i165+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i165+", 0.0)).xyz);");}}else if(_light4.type==="point"){if(_light4.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i165+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i165+", 0.0)).xyz);");}}else if(_light4.type==="spot"){if(_light4.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i165+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i165+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i165+".rgb * lightColor"+_i165+".a);");}src.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top +src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vViewPosition = viewPosition;");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var lightsState=scene._lightsState;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching flat-shading draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i164=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i164> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i166=0,_len23=sectionPlanesState.getNumAllocatedSectionPlanes();_i166<_len23;_i166++){src.push("if (sectionPlaneActive"+_i166+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i166+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i166+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var _i167=0,_len24=lightsState.lights.length;_i167<_len24;_i167++){var _light4=lightsState.lights[_i167];if(_light4.type==="ambient"){continue;}if(_light4.type==="dir"){if(_light4.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i167+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i167+", 0.0)).xyz);");}}else if(_light4.type==="point"){if(_light4.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i167+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i167+", 0.0)).xyz);");}}else if(_light4.type==="spot"){if(_light4.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i167+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i167+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i167+".rgb * lightColor"+_i167+".a);");}src.push("vec4 fragColor = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewportHeight = uSAOParams[1];");src.push(" float blendCutoff = uSAOParams[2];");src.push(" float blendFactor = uSAOParams[3];");src.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);");src.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;");src.push(" outColor = vec4(fragColor.rgb * ambient, 1.0);");}else{src.push(" outColor = fragColor;");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return TrianglesFlatColorRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesSilhouetteRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen3){_inherits(TrianglesSilhouetteRenderer$1,_TrianglesBatchingRen3);var _super50=_createSuper(TrianglesSilhouetteRenderer$1);function TrianglesSilhouetteRenderer$1(){_classCallCheck(this,TrianglesSilhouetteRenderer$1);return _super50.apply(this,arguments);}_createClass(TrianglesSilhouetteRenderer$1,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){_get(_getPrototypeOf(TrianglesSilhouetteRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,batchingLayer,renderPass,{colorUniform:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching silhouette vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 color;");this._addMatricesUniformBlockLines(src);src.push("uniform vec4 silhouetteColor;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// silhouetteFlag = NOT_RENDERED | SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | SILHOUETTE_XRAYED // renderPass = SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED src.push("int silhouetteFlag = int(flags) >> 4 & 0xF;");src.push("if (silhouetteFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var i;var len;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(i=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i166=0,_len25=sectionPlanesState.getNumAllocatedSectionPlanes();_i166<_len25;_i166++){src.push("if (sectionPlaneActive"+_i166+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i166+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i166+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = newColor;");src.push("}");return src;}}]);return TrianglesSilhouetteRenderer$1;}(TrianglesBatchingRenderer);/** +src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var i;var len;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(i=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i168=0,_len25=sectionPlanesState.getNumAllocatedSectionPlanes();_i168<_len25;_i168++){src.push("if (sectionPlaneActive"+_i168+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i168+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i168+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = newColor;");src.push("}");return src;}}]);return TrianglesSilhouetteRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var EdgesRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen4){_inherits(EdgesRenderer$1,_TrianglesBatchingRen4);var _super51=_createSuper(EdgesRenderer$1);function EdgesRenderer$1(scene){_classCallCheck(this,EdgesRenderer$1);return _super51.call(this,scene,false,{instancing:false,edges:true});}return _createClass(EdgesRenderer$1);}(TrianglesBatchingRenderer);/** * @private */var EdgesEmphasisRenderer$1=/*#__PURE__*/function(_EdgesRenderer$){_inherits(EdgesEmphasisRenderer$1,_EdgesRenderer$);var _super52=_createSuper(EdgesEmphasisRenderer$1);function EdgesEmphasisRenderer$1(){_classCallCheck(this,EdgesEmphasisRenderer$1);return _super52.apply(this,arguments);}_createClass(EdgesEmphasisRenderer$1,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){_get(_getPrototypeOf(EdgesEmphasisRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,batchingLayer,renderPass,{colorUniform:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesEmphasisRenderer vertex shader");src.push("uniform int renderPass;");src.push("uniform vec4 color;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// edgeFlag = NOT_RENDERED | EDGES_COLOR_OPAQUE | EDGES_COLOR_TRANSPARENT | EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED // renderPass = EDGES_COLOR_OPAQUE | EDGES_COLOR_TRANSPARENT | EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED src.push("int edgeFlag = int(flags) >> 8 & 0xF;");src.push("if (edgeFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesEmphasisRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i167=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i167> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i168=0,_len26=sectionPlanesState.getNumAllocatedSectionPlanes();_i168<_len26;_i168++){src.push("if (sectionPlaneActive"+_i168+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i168+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i168+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesEmphasisRenderer$1;}(EdgesRenderer$1);/** +src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesEmphasisRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i169=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i169> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i170=0,_len26=sectionPlanesState.getNumAllocatedSectionPlanes();_i170<_len26;_i170++){src.push("if (sectionPlaneActive"+_i170+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i170+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i170+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesEmphasisRenderer$1;}(EdgesRenderer$1);/** * @private */var EdgesColorRenderer$1=/*#__PURE__*/function(_EdgesRenderer$2){_inherits(EdgesColorRenderer$1,_EdgesRenderer$2);var _super53=_createSuper(EdgesColorRenderer$1);function EdgesColorRenderer$1(){_classCallCheck(this,EdgesColorRenderer$1);return _super53.apply(this,arguments);}_createClass(EdgesColorRenderer$1,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){_get(_getPrototypeOf(EdgesColorRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,batchingLayer,renderPass,{colorUniform:false});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry edges drawing vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// edgeFlag = NOT_RENDERED | EDGES_COLOR_OPAQUE | EDGES_COLOR_TRANSPARENT | EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED // renderPass = EDGES_COLOR_OPAQUE | EDGES_COLOR_TRANSPARENT src.push("int edgeFlag = int(flags) >> 8 & 0xF;");src.push("if (edgeFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");//src.push("vColor = vec4(float(color.r-100.0) / 255.0, float(color.g-100.0) / 255.0, float(color.b-100.0) / 255.0, float(color.a) / 255.0);"); -src.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);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry edges drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i169=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i169> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i170=0,_len27=sectionPlanesState.getNumAllocatedSectionPlanes();_i170<_len27;_i170++){src.push("if (sectionPlaneActive"+_i170+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i170+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i170+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesColorRenderer$1;}(EdgesRenderer$1);/** +src.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);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry edges drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i171=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i171> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i172=0,_len27=sectionPlanesState.getNumAllocatedSectionPlanes();_i172<_len27;_i172++){src.push("if (sectionPlaneActive"+_i172+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i172+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i172+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesColorRenderer$1;}(EdgesRenderer$1);/** * @private */var TrianglesPickMeshRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen5){_inherits(TrianglesPickMeshRenderer$1,_TrianglesBatchingRen5);var _super54=_createSuper(TrianglesPickMeshRenderer$1);function TrianglesPickMeshRenderer$1(){_classCallCheck(this,TrianglesPickMeshRenderer$1);return _super54.apply(this,arguments);}_createClass(TrianglesPickMeshRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 pickColor;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}this._addRemapClipPosLines(src);src.push("out vec4 vPickColor;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i171=0;_i171 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vPickColor; ");src.push("}");return src;}}]);return TrianglesPickMeshRenderer$1;}(TrianglesBatchingRenderer);/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i173=0;_i173 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vPickColor; ");src.push("}");return src;}}]);return TrianglesPickMeshRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesPickDepthRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen6){_inherits(TrianglesPickDepthRenderer$1,_TrianglesBatchingRen6);var _super55=_createSuper(TrianglesPickDepthRenderer$1);function TrianglesPickDepthRenderer$1(){_classCallCheck(this,TrianglesPickDepthRenderer$1);return _super55.apply(this,arguments);}_createClass(TrianglesPickDepthRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}this._addRemapClipPosLines(src);src.push("out vec4 vViewPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i172=0;_i172 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i174=0;_i174 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth src.push("}");return src;}}]);return TrianglesPickDepthRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesPickNormalsRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen7){_inherits(TrianglesPickNormalsRenderer$1,_TrianglesBatchingRen7);var _super56=_createSuper(TrianglesPickNormalsRenderer$1);function TrianglesPickNormalsRenderer$1(){_classCallCheck(this,TrianglesPickNormalsRenderer$1);return _super56.apply(this,arguments);}_createClass(TrianglesPickNormalsRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick normals vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec3 normal;");src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src,3);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec3 vWorldNormal;");src.push("out vec4 outColor;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec3 worldNormal = octDecode(normal.xy); ");src.push(" vWorldNormal = worldNormal;");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i173=0;_i173 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outNormal = ivec4(vWorldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsRenderer$1;}(TrianglesBatchingRenderer);/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec3 worldNormal = octDecode(normal.xy); ");src.push(" vWorldNormal = worldNormal;");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i175=0;_i175 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outNormal = ivec4(vWorldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesOcclusionRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen8){_inherits(TrianglesOcclusionRenderer$1,_TrianglesBatchingRen8);var _super57=_createSuper(TrianglesOcclusionRenderer$1);function TrianglesOcclusionRenderer$1(){_classCallCheck(this,TrianglesOcclusionRenderer$1);return _super57.apply(this,arguments);}_createClass(TrianglesOcclusionRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching occlusion vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");this._addMatricesUniformBlockLines(src);if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE // Only opaque objects can be occluders src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching occlusion fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i174=0;_i174> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i175=0;_i175 0.0) { discard; }");src.push(" }");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching occlusion fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i176=0;_i176> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i177=0;_i177 0.0) { discard; }");src.push(" }");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue src.push("}");return src;}}]);return TrianglesOcclusionRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesDepthRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen9){_inherits(TrianglesDepthRenderer$1,_TrianglesBatchingRen9);var _super58=_createSuper(TrianglesDepthRenderer$1);function TrianglesDepthRenderer$1(){_classCallCheck(this,TrianglesDepthRenderer$1);return _super58.apply(this,arguments);}_createClass(TrianglesDepthRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec2 vHighPrecisionZW;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vHighPrecisionZW = gl_Position.zw;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching depth fragment shader");src.push("precision highp float;");src.push("precision highp int;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i176=0;_i176> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;");src.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); ");src.push("}");return src;}}]);return TrianglesDepthRenderer$1;}(TrianglesBatchingRenderer);/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vHighPrecisionZW = gl_Position.zw;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching depth fragment shader");src.push("precision highp float;");src.push("precision highp int;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i178=0;_i178> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;");src.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); ");src.push("}");return src;}}]);return TrianglesDepthRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesNormalsRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen10){_inherits(TrianglesNormalsRenderer$1,_TrianglesBatchingRen10);var _super59=_createSuper(TrianglesNormalsRenderer$1);function TrianglesNormalsRenderer$1(){_classCallCheck(this,TrianglesNormalsRenderer$1);return _super59.apply(this,arguments);}_createClass(TrianglesNormalsRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec3 normal;");src.push("in vec4 color;");src.push("in float flags;");this._addMatricesUniformBlockLines(src,true);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec3 vViewNormal;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE -src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i177=0;_i177> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesNormalsRenderer$1;}(TrianglesBatchingRenderer);/** +src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i179=0;_i179> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesNormalsRenderer$1;}(TrianglesBatchingRenderer);/** * Renders BatchingLayer fragment depths to a shadow map. * * @private - */var TrianglesShadowRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen11){_inherits(TrianglesShadowRenderer$1,_TrianglesBatchingRen11);var _super60=_createSuper(TrianglesShadowRenderer$1);function TrianglesShadowRenderer$1(){_classCallCheck(this,TrianglesShadowRenderer$1);return _super60.apply(this,arguments);}_createClass(TrianglesShadowRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry shadow vertex shader");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("uniform mat4 shadowViewMatrix;");src.push("uniform mat4 shadowProjMatrix;");this._addMatricesUniformBlockLines(src);if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 outColor;");src.push("void main(void) {");src.push(" int colorFlag = int(flags) & 0xF;");src.push(" bool visible = (colorFlag > 0);");src.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);");src.push(" if (!visible || transparent) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry shadow fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i178=0;_i178> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}src.push(" outColor = encodeFloat( gl_FragCoord.z); ");src.push("}");return src;}}]);return TrianglesShadowRenderer$1;}(TrianglesBatchingRenderer);// const TEXTURE_DECODE_FUNCS = {}; + */var TrianglesShadowRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen11){_inherits(TrianglesShadowRenderer$1,_TrianglesBatchingRen11);var _super60=_createSuper(TrianglesShadowRenderer$1);function TrianglesShadowRenderer$1(){_classCallCheck(this,TrianglesShadowRenderer$1);return _super60.apply(this,arguments);}_createClass(TrianglesShadowRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry shadow vertex shader");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("uniform mat4 shadowViewMatrix;");src.push("uniform mat4 shadowProjMatrix;");this._addMatricesUniformBlockLines(src);if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 outColor;");src.push("void main(void) {");src.push(" int colorFlag = int(flags) & 0xF;");src.push(" bool visible = (colorFlag > 0);");src.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);");src.push(" if (!visible || transparent) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry shadow fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i180=0;_i180> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}src.push(" outColor = encodeFloat( gl_FragCoord.z); ");src.push("}");return src;}}]);return TrianglesShadowRenderer$1;}(TrianglesBatchingRenderer);// const TEXTURE_DECODE_FUNCS = {}; // TEXTURE_DECODE_FUNCS[LinearEncoding] = "linearToLinear"; // TEXTURE_DECODE_FUNCS[sRGBEncoding] = "sRGBToLinear"; /** @@ -14625,7 +14628,7 @@ src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderP // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");src.push("vFragDepth = 1.0 + clipPos.w;");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");if(clippingCaps){src.push("vClipPosition = clipPos;");}}src.push("vViewPosition = viewPosition;");src.push("vViewNormal = viewNormal;");src.push("vColor = color;");src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");src.push("vMetallicRoughness = metallicRoughness;");if(lightsState.lightMaps.length>0){src.push("vWorldNormal = worldNormal.xyz;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. -var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var clippingCaps=sectionPlanesState.clippingCaps;var src=[];src.push('#version 300 es');src.push("// Triangles batching quality draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");src.push("uniform sampler2D uMetallicRoughMap;");src.push("uniform sampler2D uEmissiveMap;");src.push("uniform sampler2D uNormalMap;");src.push("uniform sampler2D uAOMap;");src.push("in vec4 vViewPosition;");src.push("in vec3 vViewNormal;");src.push("in vec4 vColor;");src.push("in vec2 vUV;");src.push("in vec2 vMetallicRoughness;");if(lightsState.lightMaps.length>0){src.push("in vec3 vWorldNormal;");}this._addMatricesUniformBlockLines(src,true);if(lightsState.reflectionMaps.length>0){src.push("uniform samplerCube reflectionMap;");}if(lightsState.lightMaps.length>0){src.push("uniform samplerCube lightMap;");}src.push("uniform vec4 lightAmbient;");for(var _i179=0,len=lightsState.lights.length;_i1790;var clippingCaps=sectionPlanesState.clippingCaps;var src=[];src.push('#version 300 es');src.push("// Triangles batching quality draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");src.push("uniform sampler2D uMetallicRoughMap;");src.push("uniform sampler2D uEmissiveMap;");src.push("uniform sampler2D uNormalMap;");src.push("uniform sampler2D uAOMap;");src.push("in vec4 vViewPosition;");src.push("in vec3 vViewNormal;");src.push("in vec4 vColor;");src.push("in vec2 vUV;");src.push("in vec2 vMetallicRoughness;");if(lightsState.lightMaps.length>0){src.push("in vec3 vWorldNormal;");}this._addMatricesUniformBlockLines(src,true);if(lightsState.reflectionMaps.length>0){src.push("uniform samplerCube reflectionMap;");}if(lightsState.lightMaps.length>0){src.push("uniform samplerCube lightMap;");}src.push("uniform vec4 lightAmbient;");for(var _i181=0,len=lightsState.lights.length;_i1810){src.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {");src.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);");//TODO: a random factor - fix this src.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;");src.push(" return envMapColor;");src.push("}");}// SPECULAR BRDF EVALUATION src.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {");src.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );");src.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;");src.push("}");src.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );");src.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );");src.push(" return 1.0 / ( gl * gv );");src.push("}");src.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );");src.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );");src.push(" return 0.5 / max( gv + gl, EPSILON );");src.push("}");src.push("float D_GGX(const in float alpha, const in float dotNH) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;");src.push(" return RECIPROCAL_PI * a2 / ( denom * denom);");src.push("}");src.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {");src.push(" float alpha = ( roughness * roughness );");src.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );");src.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );");src.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );");src.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );");src.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );");src.push(" vec3 F = F_Schlick( specularColor, dotLH );");src.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );");src.push(" float D = D_GGX( alpha, dotNH );");src.push(" return F * (G * D);");src.push("}");src.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {");src.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));");src.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);");src.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);");src.push(" vec4 r = roughness * c0 + c1;");src.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;");src.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;");src.push(" return specularColor * AB.x + AB.y;");src.push("}");if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");if(lightsState.lightMaps.length>0){src.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;");src.push(" irradiance *= PI;");src.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;");}if(lightsState.reflectionMaps.length>0){src.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);");src.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);");src.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);");src.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);");src.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);");src.push(" reflectedLight.specular += radiance * specularBRDFContrib;");}src.push("}");}// MAIN LIGHTING COMPUTATION FUNCTION -src.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");src.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));");src.push(" vec3 irradiance = dotNL * incidentLight.color * PI;");src.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);");src.push("}");src.push("out vec4 outColor;");src.push("void main(void) {");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i181=0,_len29=sectionPlanesState.getNumAllocatedSectionPlanes();_i181<_len29;_i181++){src.push("if (sectionPlaneActive"+_i181+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i181+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i181+".xyz), 0.0, 1000.0);");src.push("}");}if(clippingCaps){src.push(" if (dist > (0.002 * vClipPosition.w)) {");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);");if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" return;");src.push("}");}else{src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");}src.push("}");}src.push("IncidentLight light;");src.push("Material material;");src.push("Geometry geometry;");src.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));");src.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));");src.push("float opacity = float(vColor.a) / 255.0;");src.push("vec3 baseColor = rgb;");src.push("float specularF0 = 1.0;");src.push("float metallic = float(vMetallicRoughness.r) / 255.0;");src.push("float roughness = float(vMetallicRoughness.g) / 255.0;");src.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;");src.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));");src.push("baseColor *= colorTexel.rgb;");// src.push("opacity *= colorTexel.a;"); -src.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;");src.push("metallic *= metalRoughTexel.b;");src.push("roughness *= metalRoughTexel.g;");src.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );");src.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);");src.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);");src.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);");src.push("geometry.position = vViewPosition.xyz;");src.push("geometry.viewNormal = -normalize(viewNormal);");src.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);");if(lightsState.lightMaps.length>0){src.push("geometry.worldNormal = normalize(vWorldNormal);");}if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("computePBRLightMapping(geometry, material, reflectedLight);");}for(var _i182=0,_len30=lightsState.lights.length;_i182<_len30;_i182++){var _light5=lightsState.lights[_i182];if(_light5.type==="ambient"){continue;}if(_light5.type==="dir"){if(_light5.space==="view"){src.push("light.direction = normalize(lightDir"+_i182+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i182+", 0.0)).xyz);");}}else if(_light5.type==="point"){if(_light5.space==="view"){src.push("light.direction = normalize(lightPos"+_i182+" - vViewPosition.xyz);");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightPos"+_i182+", 0.0)).xyz);");}}else if(_light5.type==="spot"){if(_light5.space==="view"){src.push("light.direction = normalize(lightDir"+_i182+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i182+", 0.0)).xyz);");}}else{continue;}src.push("light.color = lightColor"+_i182+".rgb * lightColor"+_i182+".a;");// a is intensity +src.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");src.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));");src.push(" vec3 irradiance = dotNL * incidentLight.color * PI;");src.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);");src.push("}");src.push("out vec4 outColor;");src.push("void main(void) {");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i183=0,_len29=sectionPlanesState.getNumAllocatedSectionPlanes();_i183<_len29;_i183++){src.push("if (sectionPlaneActive"+_i183+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i183+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i183+".xyz), 0.0, 1000.0);");src.push("}");}if(clippingCaps){src.push(" if (dist > (0.002 * vClipPosition.w)) {");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);");if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" return;");src.push("}");}else{src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");}src.push("}");}src.push("IncidentLight light;");src.push("Material material;");src.push("Geometry geometry;");src.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));");src.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));");src.push("float opacity = float(vColor.a) / 255.0;");src.push("vec3 baseColor = rgb;");src.push("float specularF0 = 1.0;");src.push("float metallic = float(vMetallicRoughness.r) / 255.0;");src.push("float roughness = float(vMetallicRoughness.g) / 255.0;");src.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;");src.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));");src.push("baseColor *= colorTexel.rgb;");// src.push("opacity *= colorTexel.a;"); +src.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;");src.push("metallic *= metalRoughTexel.b;");src.push("roughness *= metalRoughTexel.g;");src.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );");src.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);");src.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);");src.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);");src.push("geometry.position = vViewPosition.xyz;");src.push("geometry.viewNormal = -normalize(viewNormal);");src.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);");if(lightsState.lightMaps.length>0){src.push("geometry.worldNormal = normalize(vWorldNormal);");}if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("computePBRLightMapping(geometry, material, reflectedLight);");}for(var _i184=0,_len30=lightsState.lights.length;_i184<_len30;_i184++){var _light5=lightsState.lights[_i184];if(_light5.type==="ambient"){continue;}if(_light5.type==="dir"){if(_light5.space==="view"){src.push("light.direction = normalize(lightDir"+_i184+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i184+", 0.0)).xyz);");}}else if(_light5.type==="point"){if(_light5.space==="view"){src.push("light.direction = normalize(lightPos"+_i184+" - vViewPosition.xyz);");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightPos"+_i184+", 0.0)).xyz);");}}else if(_light5.type==="spot"){if(_light5.space==="view"){src.push("light.direction = normalize(lightDir"+_i184+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i184+", 0.0)).xyz);");}}else{continue;}src.push("light.color = lightColor"+_i184+".rgb * lightColor"+_i184+".a;");// a is intensity src.push("computePBRLighting(light, geometry, material, reflectedLight);");}src.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;");// TODO: correct gamma function src.push("float aoFactor = texture(uAOMap, vUV).r;");src.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;");src.push("vec4 fragColor;");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject @@ -14644,13 +14647,13 @@ src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewp */var TrianglesPickNormalsFlatRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen13){_inherits(TrianglesPickNormalsFlatRenderer$1,_TrianglesBatchingRen13);var _super62=_createSuper(TrianglesPickNormalsFlatRenderer$1);function TrianglesPickNormalsFlatRenderer$1(){_classCallCheck(this,TrianglesPickNormalsFlatRenderer$1);return _super62.apply(this,arguments);}_createClass(TrianglesPickNormalsFlatRenderer$1,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick flat normals vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src,3);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick flat normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i183=0;_i183 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsFlatRenderer$1;}(TrianglesBatchingRenderer);/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching pick flat normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("in float vFlags;");for(var i=0;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i185=0;_i185 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsFlatRenderer$1;}(TrianglesBatchingRenderer);/** * @private */var TrianglesColorTextureRenderer$1=/*#__PURE__*/function(_TrianglesBatchingRen14){_inherits(TrianglesColorTextureRenderer$1,_TrianglesBatchingRen14);var _super63=_createSuper(TrianglesColorTextureRenderer$1);function TrianglesColorTextureRenderer$1(){_classCallCheck(this,TrianglesColorTextureRenderer$1);return _super63.apply(this,arguments);}_createClass(TrianglesColorTextureRenderer$1,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene.gammaOutput,scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(TrianglesColorTextureRenderer$1.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching color texture vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");src.push("in vec2 uv;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}this._addMatricesUniformBlockLines(src);src.push("uniform mat3 uvDecodeMatrix;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 vColor;");src.push("out vec2 vUV;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vViewPosition = viewPosition;");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. -var lightsState=scene._lightsState;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching color texture fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}src.push("uniform float gammaFactor;");src.push("vec4 linearToLinear( in vec4 value ) {");src.push(" return value;");src.push("}");src.push("vec4 sRGBToLinear( in vec4 value ) {");src.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 );");src.push("}");src.push("vec4 gammaToLinear( in vec4 value) {");src.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );");src.push("}");if(gammaOutput){src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i184=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i184> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i186=0,_len32=sectionPlanesState.getNumAllocatedSectionPlanes();_i186<_len32;_i186++){src.push("if (sectionPlaneActive"+_i186+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i186+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i186+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var _i187=0,_len33=lightsState.lights.length;_i187<_len33;_i187++){var _light6=lightsState.lights[_i187];if(_light6.type==="ambient"){continue;}if(_light6.type==="dir"){if(_light6.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i187+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i187+", 0.0)).xyz);");}}else if(_light6.type==="point"){if(_light6.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i187+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i187+", 0.0)).xyz);");}}else if(_light6.type==="spot"){if(_light6.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i187+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i187+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i187+".rgb * lightColor"+_i187+".a);");}src.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);");if(gammaOutput){src.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));");}else{src.push("vec4 colorTexel = color * texture(uColorMap, vUV);");}src.push("float opacity = color.a;");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top +var lightsState=scene._lightsState;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Triangles batching color texture fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}src.push("uniform float gammaFactor;");src.push("vec4 linearToLinear( in vec4 value ) {");src.push(" return value;");src.push("}");src.push("vec4 sRGBToLinear( in vec4 value ) {");src.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 );");src.push("}");src.push("vec4 gammaToLinear( in vec4 value) {");src.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );");src.push("}");if(gammaOutput){src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i186=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i186> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i188=0,_len32=sectionPlanesState.getNumAllocatedSectionPlanes();_i188<_len32;_i188++){src.push("if (sectionPlaneActive"+_i188+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i188+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i188+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var _i189=0,_len33=lightsState.lights.length;_i189<_len33;_i189++){var _light6=lightsState.lights[_i189];if(_light6.type==="ambient"){continue;}if(_light6.type==="dir"){if(_light6.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i189+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i189+", 0.0)).xyz);");}}else if(_light6.type==="point"){if(_light6.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i189+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i189+", 0.0)).xyz);");}}else if(_light6.type==="spot"){if(_light6.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i189+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i189+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i189+".rgb * lightColor"+_i189+".a);");}src.push("vec4 color = vec4((lightAmbient.rgb * lightAmbient.a * newColor.rgb) + (reflectedColor * newColor.rgb), newColor.a);");if(gammaOutput){src.push("vec4 colorTexel = color * sRGBToLinear(texture(uColorMap, vUV));");}else{src.push("vec4 colorTexel = color * texture(uColorMap, vUV);");}src.push("float opacity = color.a;");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewportHeight = uSAOParams[1];");src.push(" float blendCutoff = uSAOParams[2];");src.push(" float blendFactor = uSAOParams[3];");src.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);");src.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;");src.push(" outColor = vec4(colorTexel.rgb * ambient, opacity);");}else{src.push(" outColor = vec4(colorTexel.rgb, opacity);");}if(gammaOutput){src.push("outColor = linearToGamma(outColor, gammaFactor);");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return TrianglesColorTextureRenderer$1;}(TrianglesBatchingRenderer);var tempVec3a$B=math.vec3();var tempVec3b$x=math.vec3();var tempVec3c$s=math.vec3();var tempVec3d$c=math.vec3();var tempMat4a$q=math.mat4();/** * @private @@ -14662,7 +14665,7 @@ gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}this.setSectionPlanesStateUnif state.indicesBuf.bind();gl.drawElements(gl.TRIANGLES,state.indicesBuf.numItems,state.indicesBuf.itemType,0);state.indicesBuf.unbind();}},{key:"_allocate",value:function _allocate(){_get(_getPrototypeOf(TrianglesSnapInitRenderer$1.prototype),"_allocate",this).call(this);var program=this._program;{this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}this._uCameraEyeRtc=program.getLocation("uCameraEyeRtc");this.uVectorA=program.getLocation("snapVectorA");this.uInverseVectorAB=program.getLocation("snapInvVectorAB");this._uLayerNumber=program.getLocation("layerNumber");this._uCoordinateScaler=program.getLocation("coordinateScaler");}},{key:"_bindProgram",value:function _bindProgram(){this._program.bind();}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");src.push("in vec4 pickColor;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 snapVectorA;");src.push("uniform vec2 snapInvVectorAB;");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;");src.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i188=0;_i188> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapInitRenderer$1;}(VBORenderer);var tempVec3a$A=math.vec3();var tempVec3b$w=math.vec3();var tempVec3c$r=math.vec3();var tempVec3d$b=math.vec3();var tempMat4a$p=math.mat4();/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i190=0;_i190> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapInitRenderer$1;}(VBORenderer);var tempVec3a$A=math.vec3();var tempVec3b$w=math.vec3();var tempVec3c$r=math.vec3();var tempVec3d$b=math.vec3();var tempMat4a$p=math.mat4();/** * @private */var TrianglesSnapRenderer$1=/*#__PURE__*/function(_VBORenderer3){_inherits(TrianglesSnapRenderer$1,_VBORenderer3);var _super65=_createSuper(TrianglesSnapRenderer$1);function TrianglesSnapRenderer$1(){_classCallCheck(this,TrianglesSnapRenderer$1);return _super65.apply(this,arguments);}_createClass(TrianglesSnapRenderer$1,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=batchingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=batchingLayer._state;var origin=batchingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=batchingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(batchingLayer)){gl.bindVertexArray(this._vaoCache.get(batchingLayer));}else{this._vaoCache.set(batchingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$A;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$w;if(origin){var rotatedOrigin=tempVec3c$r;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$p);rtcCameraEye=tempVec3d$b;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix? @@ -14674,7 +14677,7 @@ if(frameCtx.snapMode==="edge"){state.edgeIndicesBuf.bind();gl.drawElements(gl.LI // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapBatchingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i189=0;_i189> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapRenderer$1;}(VBORenderer);/** +src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapBatchingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i191=0;_i191> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapRenderer$1;}(VBORenderer);/** * @private */var Renderers$1=/*#__PURE__*/function(){function Renderers$1(scene){_classCallCheck(this,Renderers$1);this._scene=scene;}_createClass(Renderers$1,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()){this._colorRendererWithSAO.destroy();this._colorRendererWithSAO=null;}if(this._flatColorRenderer&&!this._flatColorRenderer.getValid()){this._flatColorRenderer.destroy();this._flatColorRenderer=null;}if(this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()){this._flatColorRendererWithSAO.destroy();this._flatColorRendererWithSAO=null;}if(this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()){this._colorTextureRenderer.destroy();this._colorTextureRenderer=null;}if(this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()){this._colorTextureRendererWithSAO.destroy();this._colorTextureRendererWithSAO=null;}if(this._pbrRenderer&&!this._pbrRenderer.getValid()){this._pbrRenderer.destroy();this._pbrRenderer=null;}if(this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()){this._pbrRendererWithSAO.destroy();this._pbrRendererWithSAO=null;}if(this._depthRenderer&&!this._depthRenderer.getValid()){this._depthRenderer.destroy();this._depthRenderer=null;}if(this._normalsRenderer&&!this._normalsRenderer.getValid()){this._normalsRenderer.destroy();this._normalsRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._edgesRenderer&&!this._edgesRenderer.getValid()){this._edgesRenderer.destroy();this._edgesRenderer=null;}if(this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()){this._edgesColorRenderer.destroy();this._edgesColorRenderer=null;}if(this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()){this._pickMeshRenderer.destroy();this._pickMeshRenderer=null;}if(this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()){this._pickDepthRenderer.destroy();this._pickDepthRenderer=null;}if(this._pickNormalsRenderer&&this._pickNormalsRenderer.getValid()===false){this._pickNormalsRenderer.destroy();this._pickNormalsRenderer=null;}if(this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.getValid()===false){this._pickNormalsFlatRenderer.destroy();this._pickNormalsFlatRenderer=null;}if(this._occlusionRenderer&&this._occlusionRenderer.getValid()===false){this._occlusionRenderer.destroy();this._occlusionRenderer=null;}if(this._shadowRenderer&&!this._shadowRenderer.getValid()){this._shadowRenderer.destroy();this._shadowRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"eagerCreateRenders",value:function eagerCreateRenders(){// Pre-initialize certain renderers that would otherwise be lazy-initialised // on user interaction, such as picking or emphasis, so that there is no delay @@ -14760,7 +14763,7 @@ this._silhouetteRenderer=new TrianglesSilhouetteRenderer$1(this._scene);}if(!thi this.positions=[];this.colors=[];this.uv=[];this.metallicRoughness=[];this.normals=[];this.pickColors=[];this.offsets=[];this.indices=[];this.edgeIndices=[];});var translate=math.mat4();var scale=math.mat4();/** * @private */function quantizePositions(positions,aabb,positionsDecodeMatrix){// http://cg.postech.ac.kr/research/mesh_comp_mobile/mesh_comp_mobile_conference.pdf -var lenPositions=positions.length;var quantizedPositions=new Uint16Array(lenPositions);var xmin=aabb[0];var ymin=aabb[1];var zmin=aabb[2];var xwid=aabb[3]-xmin;var ywid=aabb[4]-ymin;var zwid=aabb[5]-zmin;var maxInt=65525;var xMultiplier=maxInt/xwid;var yMultiplier=maxInt/ywid;var zMultiplier=maxInt/zwid;var verify=function verify(num){return num>=0?num:0;};for(var _i190=0;_i190=0?num:0;};for(var _i192=0;_i1920){for(var _i194=0,_len35=normalsCompressed.length;_i194<_len35;_i194++){buffer.normals.push(normalsCompressed[_i194]);}}else if(normals&&normals.length>0){var worldNormalMatrix=tempMat4$1;if(meshMatrix){math.inverseMat4(math.transposeMat4(meshMatrix,tempMat4b),worldNormalMatrix);// Note: order of inverse and transpose doesn't matter -}else{math.identityMat4(worldNormalMatrix,worldNormalMatrix);}transformAndOctEncodeNormals(worldNormalMatrix,normals,normals.length,buffer.normals,buffer.normals.length);}if(colors){for(var _i195=0,_len36=colors.length;_i195<_len36;_i195+=3){buffer.colors.push(colors[_i195]*255);buffer.colors.push(colors[_i195+1]*255);buffer.colors.push(colors[_i195+2]*255);buffer.colors.push(255);}}else if(colorsCompressed){for(var _i196=0,_len37=colors.length;_i196<_len37;_i196+=3){buffer.colors.push(colors[_i196]);buffer.colors.push(colors[_i196+1]);buffer.colors.push(colors[_i196+2]);buffer.colors.push(255);}}else if(color){var _r3=color[0];// Color is pre-quantized by VBOSceneModel -var g=color[1];var b=color[2];var _a2=opacity;for(var _i197=0;_i1970){for(var _i199=0,_len38=uv.length;_i199<_len38;_i199++){buffer.uv.push(uv[_i199]);}}else if(uvCompressed&&uvCompressed.length>0){for(var _i200=0,_len39=uvCompressed.length;_i200<_len39;_i200++){buffer.uv.push(uvCompressed[_i200]);}}for(var _i201=0,_len40=indices.length;_i201<_len40;_i201++){buffer.indices.push(vertsBaseIndex+indices[_i201]);}if(edgeIndices){for(var _i202=0,_len41=edgeIndices.length;_i202<_len41;_i202++){buffer.edgeIndices.push(vertsBaseIndex+edgeIndices[_i202]);}}{var pickColorsBase=buffer.pickColors.length;var lenPickColors=numVerts*4;for(var _i203=pickColorsBase,_len42=pickColorsBase+lenPickColors;_i203<_len42;_i203+=4){buffer.pickColors.push(pickColor[0]);buffer.pickColors.push(pickColor[1]);buffer.pickColors.push(pickColor[2]);buffer.pickColors.push(pickColor[3]);}}if(scene.entityOffsetsEnabled){for(var _i204=0;_i2040){for(var _i196=0,_len35=normalsCompressed.length;_i196<_len35;_i196++){buffer.normals.push(normalsCompressed[_i196]);}}else if(normals&&normals.length>0){var worldNormalMatrix=tempMat4$1;if(meshMatrix){math.inverseMat4(math.transposeMat4(meshMatrix,tempMat4b),worldNormalMatrix);// Note: order of inverse and transpose doesn't matter +}else{math.identityMat4(worldNormalMatrix,worldNormalMatrix);}transformAndOctEncodeNormals(worldNormalMatrix,normals,normals.length,buffer.normals,buffer.normals.length);}if(colors){for(var _i197=0,_len36=colors.length;_i197<_len36;_i197+=3){buffer.colors.push(colors[_i197]*255);buffer.colors.push(colors[_i197+1]*255);buffer.colors.push(colors[_i197+2]*255);buffer.colors.push(255);}}else if(colorsCompressed){for(var _i198=0,_len37=colors.length;_i198<_len37;_i198+=3){buffer.colors.push(colors[_i198]);buffer.colors.push(colors[_i198+1]);buffer.colors.push(colors[_i198+2]);buffer.colors.push(255);}}else if(color){var _r3=color[0];// Color is pre-quantized by VBOSceneModel +var g=color[1];var b=color[2];var _a2=opacity;for(var _i199=0;_i1990){for(var _i201=0,_len38=uv.length;_i201<_len38;_i201++){buffer.uv.push(uv[_i201]);}}else if(uvCompressed&&uvCompressed.length>0){for(var _i202=0,_len39=uvCompressed.length;_i202<_len39;_i202++){buffer.uv.push(uvCompressed[_i202]);}}for(var _i203=0,_len40=indices.length;_i203<_len40;_i203++){buffer.indices.push(vertsBaseIndex+indices[_i203]);}if(edgeIndices){for(var _i204=0,_len41=edgeIndices.length;_i204<_len41;_i204++){buffer.edgeIndices.push(vertsBaseIndex+edgeIndices[_i204]);}}{var pickColorsBase=buffer.pickColors.length;var lenPickColors=numVerts*4;for(var _i205=pickColorsBase,_len42=pickColorsBase+lenPickColors;_i205<_len42;_i205+=4){buffer.pickColors.push(pickColor[0]);buffer.pickColors.push(pickColor[1]);buffer.pickColors.push(pickColor[2]);buffer.pickColors.push(pickColor[3]);}}if(scene.entityOffsetsEnabled){for(var _i206=0;_i2060){var quantizedPositions=this._state.positionsDecodeMatrix?new Uint16Array(buffer.positions):quantizePositions(buffer.positions,this._modelAABB,this._state.positionsDecodeMatrix=math.mat4());// BOTTLENECK -state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,quantizedPositions,quantizedPositions.length,3,gl.STATIC_DRAW);if(this.model.scene.pickSurfacePrecisionEnabled){for(var _i205=0,numPortions=this._portions.length;_i2050){// Normals are already oct-encoded +state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,quantizedPositions,quantizedPositions.length,3,gl.STATIC_DRAW);if(this.model.scene.pickSurfacePrecisionEnabled){for(var _i207=0,numPortions=this._portions.length;_i2070){// Normals are already oct-encoded var normals=new Int8Array(buffer.normals);var normalized=true;// For oct encoded UInts state.normalsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,normals,buffer.normals.length,3,gl.STATIC_DRAW,normalized);}if(buffer.colors.length>0){// Colors are already compressed var colors=new Uint8Array(buffer.colors);var _normalized=false;state.colorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,colors,buffer.colors.length,4,gl.DYNAMIC_DRAW,_normalized);}if(buffer.uv.length>0){if(!state.uvDecodeMatrix){var bounds=geometryCompressionUtils.getUVBounds(buffer.uv);var result=geometryCompressionUtils.compressUVs(buffer.uv,bounds.min,bounds.max);var uv=result.quantized;var notNormalized=false;state.uvDecodeMatrix=math.mat3(result.decodeMatrix);state.uvBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,uv,uv.length,2,gl.STATIC_DRAW,notNormalized);}else{var _notNormalized=false;state.uvBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,buffer.uv,buffer.uv.length,2,gl.STATIC_DRAW,_notNormalized);}}if(buffer.metallicRoughness.length>0){var metallicRoughness=new Uint8Array(buffer.metallicRoughness);var _normalized2=false;state.metallicRoughnessBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,metallicRoughness,buffer.metallicRoughness.length,2,gl.STATIC_DRAW,_normalized2);}if(buffer.positions.length>0){// Because we build flags arrays here, get their length from the positions array -var flagsLength=buffer.positions.length/3;var flags=new Float32Array(flagsLength);var _notNormalized2=false;state.flagsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,flags,flags.length,1,gl.DYNAMIC_DRAW,_notNormalized2);}if(buffer.pickColors.length>0){var pickColors=new Uint8Array(buffer.pickColors);var _normalized3=false;state.pickColorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,pickColors,buffer.pickColors.length,4,gl.STATIC_DRAW,_normalized3);}if(this.model.scene.entityOffsetsEnabled){if(buffer.offsets.length>0){var offsets=new Float32Array(buffer.offsets);state.offsetsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,offsets,buffer.offsets.length,3,gl.DYNAMIC_DRAW);}}if(buffer.indices.length>0){var indices=new Uint32Array(buffer.indices);state.indicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,indices,buffer.indices.length,1,gl.STATIC_DRAW);}if(buffer.edgeIndices.length>0){var edgeIndices=new Uint32Array(buffer.edgeIndices);state.edgeIndicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,edgeIndices,buffer.edgeIndices.length,1,gl.STATIC_DRAW);}this._state.pbrSupported=!!state.metallicRoughnessBuf&&!!state.uvBuf&&!!state.normalsBuf&&!!state.textureSet&&!!state.textureSet.colorTexture&&!!state.textureSet.metallicRoughnessTexture;this._state.colorTextureSupported=!!state.uvBuf&&!!state.textureSet&&!!state.textureSet.colorTexture;this._buffer=null;this._finalized=true;}},{key:"isEmpty",value:function isEmpty(){return!this._state.indicesBuf;}},{key:"initFlags",value:function initFlags(portionId,flags,meshTransparent){if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}if(meshTransparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}var deferred=true;this._setFlags(portionId,flags,meshTransparent,deferred);}},{key:"flushInitFlags",value:function flushInitFlags(){this._setDeferredFlags();}},{key:"setVisible",value:function setVisible(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}else{this._numVisibleLayerPortions--;this.model.numVisibleLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setHighlighted",value:function setHighlighted(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}else{this._numHighlightedLayerPortions--;this.model.numHighlightedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setXRayed",value:function setXRayed(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}else{this._numXRayedLayerPortions--;this.model.numXRayedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setSelected",value:function setSelected(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}else{this._numSelectedLayerPortions--;this.model.numSelectedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setEdges",value:function setEdges(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}else{this._numEdgesLayerPortions--;this.model.numEdgesLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setClippable",value:function setClippable(portionId,flags){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}else{this._numClippableLayerPortions--;this.model.numClippableLayerPortions--;}this._setFlags(portionId,flags);}},{key:"setCulled",value:function setCulled(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}else{this._numCulledLayerPortions--;this.model.numCulledLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setCollidable",value:function setCollidable(portionId,flags){if(!this._finalized){throw"Not finalized";}}},{key:"setPickable",value:function setPickable(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}else{this._numPickableLayerPortions--;this.model.numPickableLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setColor",value:function setColor(portionId,color){if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId;var portion=this._portions[portionsIdx];var vertsBaseIndex=portion.vertsBaseIndex;var numVerts=portion.numVerts;var firstColor=vertsBaseIndex*4;var lenColor=numVerts*4;var tempArray=this._scratchMemory.getUInt8Array(lenColor);var r=color[0];var g=color[1];var b=color[2];var a=color[3];for(var _i206=0;_i2060){var pickColors=new Uint8Array(buffer.pickColors);var _normalized3=false;state.pickColorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,pickColors,buffer.pickColors.length,4,gl.STATIC_DRAW,_normalized3);}if(this.model.scene.entityOffsetsEnabled){if(buffer.offsets.length>0){var offsets=new Float32Array(buffer.offsets);state.offsetsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,offsets,buffer.offsets.length,3,gl.DYNAMIC_DRAW);}}if(buffer.indices.length>0){var indices=new Uint32Array(buffer.indices);state.indicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,indices,buffer.indices.length,1,gl.STATIC_DRAW);}if(buffer.edgeIndices.length>0){var edgeIndices=new Uint32Array(buffer.edgeIndices);state.edgeIndicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,edgeIndices,buffer.edgeIndices.length,1,gl.STATIC_DRAW);}this._state.pbrSupported=!!state.metallicRoughnessBuf&&!!state.uvBuf&&!!state.normalsBuf&&!!state.textureSet&&!!state.textureSet.colorTexture&&!!state.textureSet.metallicRoughnessTexture;this._state.colorTextureSupported=!!state.uvBuf&&!!state.textureSet&&!!state.textureSet.colorTexture;this._buffer=null;this._finalized=true;}},{key:"isEmpty",value:function isEmpty(){return!this._state.indicesBuf;}},{key:"initFlags",value:function initFlags(portionId,flags,meshTransparent){if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}if(meshTransparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}var deferred=true;this._setFlags(portionId,flags,meshTransparent,deferred);}},{key:"flushInitFlags",value:function flushInitFlags(){this._setDeferredFlags();}},{key:"setVisible",value:function setVisible(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}else{this._numVisibleLayerPortions--;this.model.numVisibleLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setHighlighted",value:function setHighlighted(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}else{this._numHighlightedLayerPortions--;this.model.numHighlightedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setXRayed",value:function setXRayed(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}else{this._numXRayedLayerPortions--;this.model.numXRayedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setSelected",value:function setSelected(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}else{this._numSelectedLayerPortions--;this.model.numSelectedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setEdges",value:function setEdges(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}else{this._numEdgesLayerPortions--;this.model.numEdgesLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setClippable",value:function setClippable(portionId,flags){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}else{this._numClippableLayerPortions--;this.model.numClippableLayerPortions--;}this._setFlags(portionId,flags);}},{key:"setCulled",value:function setCulled(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}else{this._numCulledLayerPortions--;this.model.numCulledLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setCollidable",value:function setCollidable(portionId,flags){if(!this._finalized){throw"Not finalized";}}},{key:"setPickable",value:function setPickable(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}else{this._numPickableLayerPortions--;this.model.numPickableLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setColor",value:function setColor(portionId,color){if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId;var portion=this._portions[portionsIdx];var vertsBaseIndex=portion.vertsBaseIndex;var numVerts=portion.numVerts;var firstColor=vertsBaseIndex*4;var lenColor=numVerts*4;var tempArray=this._scratchMemory.getUInt8Array(lenColor);var r=color[0];var g=color[1];var b=color[2];var a=color[3];for(var _i208=0;_i2083&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId;var portion=this._portions[portionsIdx];var vertsBaseIndex=portion.vertsBaseIndex;var numVerts=portion.numVerts;var firstFlag=vertsBaseIndex;var lenFlags=numVerts;var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);var edges=!!(flags&ENTITY_FLAGS.EDGES);var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);var colorFlag;if(!visible||culled||xrayed||highlighted&&!this.model.scene.highlightMaterial.glowThrough||selected&&!this.model.scene.selectedMaterial.glowThrough){colorFlag=RENDER_PASSES.NOT_RENDERED;}else{if(transparent){colorFlag=RENDER_PASSES.COLOR_TRANSPARENT;}else{colorFlag=RENDER_PASSES.COLOR_OPAQUE;}}var silhouetteFlag;if(!visible||culled){silhouetteFlag=RENDER_PASSES.NOT_RENDERED;}else if(selected){silhouetteFlag=RENDER_PASSES.SILHOUETTE_SELECTED;}else if(highlighted){silhouetteFlag=RENDER_PASSES.SILHOUETTE_HIGHLIGHTED;}else if(xrayed){silhouetteFlag=RENDER_PASSES.SILHOUETTE_XRAYED;}else{silhouetteFlag=RENDER_PASSES.NOT_RENDERED;}var edgeFlag=0;if(!visible||culled){edgeFlag=RENDER_PASSES.NOT_RENDERED;}else if(selected){edgeFlag=RENDER_PASSES.EDGES_SELECTED;}else if(highlighted){edgeFlag=RENDER_PASSES.EDGES_HIGHLIGHTED;}else if(xrayed){edgeFlag=RENDER_PASSES.EDGES_XRAYED;}else if(edges){if(transparent){edgeFlag=RENDER_PASSES.EDGES_COLOR_TRANSPARENT;}else{edgeFlag=RENDER_PASSES.EDGES_COLOR_OPAQUE;}}else{edgeFlag=RENDER_PASSES.NOT_RENDERED;}var pickFlag=visible&&!culled&&pickable?RENDER_PASSES.PICK:RENDER_PASSES.NOT_RENDERED;var clippableFlag=!!(flags&ENTITY_FLAGS.CLIPPABLE)?1:0;if(deferred){// Avoid zillions of individual WebGL bufferSubData calls - buffer them to apply in one shot -if(!this._deferredFlagValues){this._deferredFlagValues=new Float32Array(this._numVerts);}for(var _i207=firstFlag,len=firstFlag+lenFlags;_i207 RTC rtcRayDir.set(worldRayDir);if(offset){math.subVec3(rtcRayOrigin,offset);}math.transformRay(this.model.worldNormalMatrix,rtcRayOrigin,rtcRayDir,rtcRayOrigin,rtcRayDir);// RTC -> local -var a=tempVec3d$a;var b=tempVec3e$1;var c=tempVec3f$1;var gotIntersect=false;var closestDist=0;var closestIntersectPos=tempVec3g$1;for(var _i211=0,len=indices.length;_i211closestDist){closestDist=dist;worldSurfacePos.set(closestIntersectPos);if(worldNormal){// Not that wasteful to eagerly compute - unlikely to hit >2 surfaces on most geometry +var a=tempVec3d$a;var b=tempVec3e$1;var c=tempVec3f$1;var gotIntersect=false;var closestDist=0;var closestIntersectPos=tempVec3g$1;for(var _i213=0,len=indices.length;_i213closestDist){closestDist=dist;worldSurfacePos.set(closestIntersectPos);if(worldNormal){// Not that wasteful to eagerly compute - unlikely to hit >2 surfaces on most geometry math.triangleNormal(a,b,c,worldNormal);}gotIntersect=true;}}}if(gotIntersect&&worldNormal){math.transformVec3(this.model.worldNormalMatrix,worldNormal,worldNormal);math.normalizeVec3(worldNormal);}return gotIntersect;}// --------- },{key:"destroy",value:function destroy(){var state=this._state;if(state.positionsBuf){state.positionsBuf.destroy();state.positionsBuf=null;}if(state.offsetsBuf){state.offsetsBuf.destroy();state.offsetsBuf=null;}if(state.normalsBuf){state.normalsBuf.destroy();state.normalsBuf=null;}if(state.colorsBuf){state.colorsBuf.destroy();state.colorsBuf=null;}if(state.metallicRoughnessBuf){state.metallicRoughnessBuf.destroy();state.metallicRoughnessBuf=null;}if(state.flagsBuf){state.flagsBuf.destroy();state.flagsBuf=null;}if(state.pickColorsBuf){state.pickColorsBuf.destroy();state.pickColorsBuf=null;}if(state.indicesBuf){state.indicesBuf.destroy();state.indicessBuf=null;}if(state.edgeIndicesBuf){state.edgeIndicesBuf.destroy();state.edgeIndicessBuf=null;}state.destroy();}}]);return VBOBatchingTrianglesLayer;}();/** * @private @@ -14882,7 +14885,7 @@ math.triangleNormal(a,b,c,worldNormal);}gotIntersect=true;}}}if(gotIntersect&&wo src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("in vec4 modelNormalMatrixCol0;");src.push("in vec4 modelNormalMatrixCol1;");src.push("in vec4 modelNormalMatrixCol2;");this._addMatricesUniformBlockLines(src,true);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("uniform vec4 lightAmbient;");for(i=0,len=lightsState.lights.length;i= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE | COLOR_TRANSPARENT src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);");src.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(i=0,len=lightsState.lights.length;i0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i212=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i212> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i213=0,_len43=sectionPlanesState.getNumAllocatedSectionPlanes();_i213<_len43;_i213++){src.push("if (sectionPlaneActive"+_i213+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i213+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i213+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top +src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);");src.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(i=0,len=lightsState.lights.length;i0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i214=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i214> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i215=0,_len43=sectionPlanesState.getNumAllocatedSectionPlanes();_i215<_len43;_i215++){src.push("if (sectionPlaneActive"+_i215+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i215+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i215+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject if(this._withSAO){src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewportHeight = uSAOParams[1];");src.push(" float blendCutoff = uSAOParams[2];");src.push(" float blendFactor = uSAOParams[3];");src.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);");src.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;");src.push(" outColor = vec4(newColor.rgb * ambient, 1.0);");}else{src.push(" outColor = newColor;");}src.push("}");return src;}}]);return TrianglesColorRenderer;}(TrianglesInstancingRenderer);/** * @private @@ -14890,7 +14893,7 @@ if(this._withSAO){src.push(" float viewportWidth = uSAOParams[0];");src.pu src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE | COLOR_TRANSPARENT src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vViewPosition = viewPosition;");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var i;var len;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry flat-shading drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i214=0,_len44=sectionPlanesState.getNumAllocatedSectionPlanes();_i214<_len44;_i214++){src.push("uniform bool sectionPlaneActive"+_i214+";");src.push("uniform vec3 sectionPlanePos"+_i214+";");src.push("uniform vec3 sectionPlaneDir"+_i214+";");}src.push("uniform float sliceThickness;");src.push("uniform vec4 sliceColor;");}this._addMatricesUniformBlockLines(src);src.push("uniform vec4 lightAmbient;");for(i=0,len=lightsState.lights.length;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i215=0,_len45=sectionPlanesState.getNumAllocatedSectionPlanes();_i215<_len45;_i215++){src.push("if (sectionPlaneActive"+_i215+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i215+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i215+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(i=0,len=lightsState.lights.length;i0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry flat-shading drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i216=0,_len44=sectionPlanesState.getNumAllocatedSectionPlanes();_i216<_len44;_i216++){src.push("uniform bool sectionPlaneActive"+_i216+";");src.push("uniform vec3 sectionPlanePos"+_i216+";");src.push("uniform vec3 sectionPlaneDir"+_i216+";");}src.push("uniform float sliceThickness;");src.push("uniform vec4 sliceColor;");}this._addMatricesUniformBlockLines(src);src.push("uniform vec4 lightAmbient;");for(i=0,len=lightsState.lights.length;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i217=0,_len45=sectionPlanesState.getNumAllocatedSectionPlanes();_i217<_len45;_i217++){src.push("if (sectionPlaneActive"+_i217+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i217+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i217+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(i=0,len=lightsState.lights.length;i> 4 & 0xF;");src.push("if (silhouetteFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing fill fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i216=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i216> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i217=0,_len46=sectionPlanesState.getNumAllocatedSectionPlanes();_i217<_len46;_i217++){src.push("if (sectionPlaneActive"+_i217+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i217+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i217+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = newColor;");src.push("}");return src;}}]);return TrianglesSilhouetteRenderer;}(TrianglesInstancingRenderer);/** +src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing fill fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i218=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i218> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i219=0,_len46=sectionPlanesState.getNumAllocatedSectionPlanes();_i219<_len46;_i219++){src.push("if (sectionPlaneActive"+_i219+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i219+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i219+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = newColor;");src.push("}");return src;}}]);return TrianglesSilhouetteRenderer;}(TrianglesInstancingRenderer);/** * @private */var EdgesRenderer=/*#__PURE__*/function(_TrianglesInstancingR4){_inherits(EdgesRenderer,_TrianglesInstancingR4);var _super70=_createSuper(EdgesRenderer);function EdgesRenderer(scene,withSAO){_classCallCheck(this,EdgesRenderer);return _super70.call(this,scene,withSAO,{instancing:true,edges:true});}return _createClass(EdgesRenderer);}(TrianglesInstancingRenderer);/** * @private @@ -14907,38 +14910,38 @@ src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4 src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// edgeFlag = NOT_RENDERED | EDGES_COLOR_OPAQUE | EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED // renderPass = EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED src.push("int edgeFlag = int(flags) >> 8 & 0xF;");src.push("if (edgeFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesEmphasisRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i218=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i218> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i219=0,_len47=sectionPlanesState.getNumAllocatedSectionPlanes();_i219<_len47;_i219++){src.push("if (sectionPlaneActive"+_i219+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i219+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i219+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesEmphasisRenderer;}(EdgesRenderer);/** +src.push("} else {");src.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesEmphasisRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i220=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i220> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i221=0,_len47=sectionPlanesState.getNumAllocatedSectionPlanes();_i221<_len47;_i221++){src.push("if (sectionPlaneActive"+_i221+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i221+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i221+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesEmphasisRenderer;}(EdgesRenderer);/** * @private */var EdgesColorRenderer=/*#__PURE__*/function(_EdgesRenderer2){_inherits(EdgesColorRenderer,_EdgesRenderer2);var _super72=_createSuper(EdgesColorRenderer);function EdgesColorRenderer(){_classCallCheck(this,EdgesColorRenderer);return _super72.apply(this,arguments);}_createClass(EdgesColorRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){_get(_getPrototypeOf(EdgesColorRenderer.prototype),"drawLayer",this).call(this,frameCtx,batchingLayer,renderPass,{colorUniform:false});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesColorRenderer vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// edgeFlag = NOT_RENDERED | EDGES_COLOR_OPAQUE | EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED // renderPass = EDGES_HIGHLIGHTED | EDGES_XRAYED | EDGES_SELECTED src.push("int edgeFlag = int(flags) >> 8 & 0xF;");src.push("if (edgeFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");// src.push("vColor = vec4(float(color.r-100.0) / 255.0, float(color.g-100.0) / 255.0, float(color.b-100.0) / 255.0, float(color.a) / 255.0);"); -src.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);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i220=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i220> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i221=0,_len48=sectionPlanesState.getNumAllocatedSectionPlanes();_i221<_len48;_i221++){src.push("if (sectionPlaneActive"+_i221+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i221+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i221+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesColorRenderer;}(EdgesRenderer);/** +src.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);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// EdgesColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i222=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i222> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i223=0,_len48=sectionPlanesState.getNumAllocatedSectionPlanes();_i223<_len48;_i223++){src.push("if (sectionPlaneActive"+_i223+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i223+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i223+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return EdgesColorRenderer;}(EdgesRenderer);/** * @private */var TrianglesPickMeshRenderer=/*#__PURE__*/function(_TrianglesInstancingR5){_inherits(TrianglesPickMeshRenderer,_TrianglesInstancingR5);var _super73=_createSuper(TrianglesPickMeshRenderer);function TrianglesPickMeshRenderer(){_classCallCheck(this,TrianglesPickMeshRenderer);return _super73.apply(this,arguments);}_createClass(TrianglesPickMeshRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry picking vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 pickColor;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vPickColor;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i222=0;_i222> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i223=0;_i223 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vPickColor; ");src.push("}");return src;}}]);return TrianglesPickMeshRenderer;}(TrianglesInstancingRenderer);/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i224=0;_i224> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i225=0;_i225 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vPickColor; ");src.push("}");return src;}}]);return TrianglesPickMeshRenderer;}(TrianglesInstancingRenderer);/** * @private */var TrianglesPickDepthRenderer=/*#__PURE__*/function(_TrianglesInstancingR6){_inherits(TrianglesPickDepthRenderer,_TrianglesInstancingR6);var _super74=_createSuper(TrianglesPickDepthRenderer);function TrianglesPickDepthRenderer(){_classCallCheck(this,TrianglesPickDepthRenderer);return _super74.apply(this,arguments);}_createClass(TrianglesPickDepthRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i224=0;_i224> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i225=0;_i225 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i226=0;_i226> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i227=0;_i227 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth src.push("}");return src;}}]);return TrianglesPickDepthRenderer;}(TrianglesInstancingRenderer);/** * @private */var TrianglesPickNormalsRenderer=/*#__PURE__*/function(_TrianglesInstancingR7){_inherits(TrianglesPickNormalsRenderer,_TrianglesInstancingR7);var _super75=_createSuper(TrianglesPickNormalsRenderer);function TrianglesPickNormalsRenderer(){_classCallCheck(this,TrianglesPickNormalsRenderer);return _super75.apply(this,arguments);}_createClass(TrianglesPickNormalsRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry normals vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec2 normal;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("in vec4 modelNormalMatrixCol0;");src.push("in vec4 modelNormalMatrixCol1;");src.push("in vec4 modelNormalMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src,3);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec3 vWorldNormal;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));");src.push(" vWorldNormal = worldNormal;");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i226=0;_i226> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outNormal = ivec4(vWorldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsRenderer;}(TrianglesInstancingRenderer);/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));");src.push(" vWorldNormal = worldNormal;");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i228=0;_i228> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outNormal = ivec4(vWorldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsRenderer;}(TrianglesInstancingRenderer);/** * @private */var TrianglesOcclusionRenderer=/*#__PURE__*/function(_TrianglesInstancingR8){_inherits(TrianglesOcclusionRenderer,_TrianglesInstancingR8);var _super76=_createSuper(TrianglesOcclusionRenderer);function TrianglesOcclusionRenderer(){_classCallCheck(this,TrianglesOcclusionRenderer);return _super76.apply(this,arguments);}_createClass(TrianglesOcclusionRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// TrianglesInstancingOcclusionRenderer vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE | COLOR_TRANSPARENT -src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// TrianglesInstancingOcclusionRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i227=0;_i227> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i228=0;_i228 0.0) { discard; }");src.push("}");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue +src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// TrianglesInstancingOcclusionRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i229=0;_i229> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i230=0;_i230 0.0) { discard; }");src.push("}");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue src.push("}");return src;}}]);return TrianglesOcclusionRenderer;}(TrianglesInstancingRenderer);/** * @private */var TrianglesDepthRenderer=/*#__PURE__*/function(_TrianglesInstancingR9){_inherits(TrianglesDepthRenderer,_TrianglesInstancingR9);var _super77=_createSuper(TrianglesDepthRenderer);function TrianglesDepthRenderer(){_classCallCheck(this,TrianglesDepthRenderer);return _super77.apply(this,arguments);}_createClass(TrianglesDepthRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth drawing vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec2 vHighPrecisionZW;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT @@ -14948,19 +14951,19 @@ src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * ve * @private */var TrianglesNormalsRenderer=/*#__PURE__*/function(_TrianglesInstancingR10){_inherits(TrianglesNormalsRenderer,_TrianglesInstancingR10);var _super78=_createSuper(TrianglesNormalsRenderer);function TrianglesNormalsRenderer(){_classCallCheck(this,TrianglesNormalsRenderer);return _super78.apply(this,arguments);}_createClass(TrianglesNormalsRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry normals drawing vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec3 normal;");src.push("in vec4 color;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src,true);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec3 vViewNormal;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE -src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i229=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i229> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i230=0,_len49=sectionPlanesState.getNumAllocatedSectionPlanes();_i230<_len49;_i230++){src.push("if (sectionPlaneActive"+_i230+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i230+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i230+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesNormalsRenderer;}(TrianglesInstancingRenderer);/** +src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i231=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i231> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i232=0,_len49=sectionPlanesState.getNumAllocatedSectionPlanes();_i232<_len49;_i232++){src.push("if (sectionPlaneActive"+_i232+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i232+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i232+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesNormalsRenderer;}(TrianglesInstancingRenderer);/** * Renders InstancingLayer fragment depths to a shadow map. * * @private */var TrianglesShadowRenderer=/*#__PURE__*/function(_TrianglesInstancingR11){_inherits(TrianglesShadowRenderer,_TrianglesInstancingR11);var _super79=_createSuper(TrianglesShadowRenderer);function TrianglesShadowRenderer(){_classCallCheck(this,TrianglesShadowRenderer);return _super79.apply(this,arguments);}_createClass(TrianglesShadowRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry shadow drawing vertex shader");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform mat4 shadowViewMatrix;");src.push("uniform mat4 shadowProjMatrix;");this._addMatricesUniformBlockLines(src);if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");src.push("int colorFlag = int(flags) & 0xF;");src.push("bool visible = (colorFlag > 0);");src.push("bool transparent = ((float(color.a) / 255.0) < 1.0);");src.push("if (!visible || transparent) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i231=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i231> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i232=0,_len50=sectionPlanesState.getNumAllocatedSectionPlanes();_i232<_len50;_i232++){src.push("if (sectionPlaneActive"+_i232+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i232+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i232+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesShadowRenderer;}(TrianglesInstancingRenderer);var TEXTURE_DECODE_FUNCS={};TEXTURE_DECODE_FUNCS[LinearEncoding]="linearToLinear";TEXTURE_DECODE_FUNCS[sRGBEncoding]="sRGBToLinear";/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i233=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i233> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i234=0,_len50=sectionPlanesState.getNumAllocatedSectionPlanes();_i234<_len50;_i234++){src.push("if (sectionPlaneActive"+_i234+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i234+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i234+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return TrianglesShadowRenderer;}(TrianglesInstancingRenderer);var TEXTURE_DECODE_FUNCS={};TEXTURE_DECODE_FUNCS[LinearEncoding]="linearToLinear";TEXTURE_DECODE_FUNCS[sRGBEncoding]="sRGBToLinear";/** * @private */var TrianglesPBRRenderer=/*#__PURE__*/function(_TrianglesInstancingR12){_inherits(TrianglesPBRRenderer,_TrianglesInstancingR12);var _super80=_createSuper(TrianglesPBRRenderer);function TrianglesPBRRenderer(){_classCallCheck(this,TrianglesPBRRenderer);return _super80.apply(this,arguments);}_createClass(TrianglesPBRRenderer,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene.gammaOutput,scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(TrianglesPBRRenderer.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var clippingCaps=sectionPlanesState.clippingCaps;var src=[];src.push("#version 300 es");src.push("// Instancing geometry quality drawing vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec3 normal;");src.push("in vec4 color;");src.push("in vec2 uv;");src.push("in vec2 metallicRoughness;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("in vec4 modelNormalMatrixCol0;");src.push("in vec4 modelNormalMatrixCol1;");src.push("in vec4 modelNormalMatrixCol2;");this._addMatricesUniformBlockLines(src,true);src.push("uniform mat3 uvDecodeMatrix;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");src.push("out vec4 vViewPosition;");src.push("out vec3 vViewNormal;");src.push("out vec4 vColor;");src.push("out vec2 vUV;");src.push("out vec2 vMetallicRoughness;");if(lightsState.lightMaps.length>0){src.push("out vec3 vWorldNormal;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");if(clippingCaps){src.push("out vec4 vClipPosition;");}}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE | COLOR_TRANSPARENT src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); ");src.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);");src.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");if(clippingCaps){src.push("vClipPosition = clipPos;");}}src.push("vViewPosition = viewPosition;");src.push("vViewNormal = viewNormal;");src.push("vColor = color;");src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");src.push("vMetallicRoughness = metallicRoughness;");if(lightsState.lightMaps.length>0){src.push("vWorldNormal = worldNormal.xyz;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. -var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var clippingCaps=sectionPlanesState.clippingCaps;var src=[];src.push("#version 300 es");src.push("// Instancing geometry quality drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");src.push("uniform sampler2D uMetallicRoughMap;");src.push("uniform sampler2D uEmissiveMap;");src.push("uniform sampler2D uNormalMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(lightsState.reflectionMaps.length>0){src.push("uniform samplerCube reflectionMap;");}if(lightsState.lightMaps.length>0){src.push("uniform samplerCube lightMap;");}src.push("uniform vec4 lightAmbient;");for(var _i233=0,len=lightsState.lights.length;_i2330){src.push("in vec3 vWorldNormal;");}this._addMatricesUniformBlockLines(src,true);// CONSTANT DEFINITIONS +var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var clippingCaps=sectionPlanesState.clippingCaps;var src=[];src.push("#version 300 es");src.push("// Instancing geometry quality drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");src.push("uniform sampler2D uMetallicRoughMap;");src.push("uniform sampler2D uEmissiveMap;");src.push("uniform sampler2D uNormalMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(lightsState.reflectionMaps.length>0){src.push("uniform samplerCube reflectionMap;");}if(lightsState.lightMaps.length>0){src.push("uniform samplerCube lightMap;");}src.push("uniform vec4 lightAmbient;");for(var _i235=0,len=lightsState.lights.length;_i2350){src.push("in vec3 vWorldNormal;");}this._addMatricesUniformBlockLines(src,true);// CONSTANT DEFINITIONS src.push("#define PI 3.14159265359");src.push("#define RECIPROCAL_PI 0.31830988618");src.push("#define RECIPROCAL_PI2 0.15915494");src.push("#define EPSILON 1e-6");src.push("#define saturate(a) clamp( a, 0.0, 1.0 )");// UTILITY DEFINITIONS src.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {");src.push(" vec3 texel = texture( uNormalMap, uv ).xyz;");src.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {");src.push(" return normalize(surf_norm );");src.push(" }");src.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );");src.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );");src.push(" vec2 st0 = dFdx( uv.st );");src.push(" vec2 st1 = dFdy( uv.st );");src.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );");src.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );");src.push(" vec3 N = normalize( surf_norm );");src.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;");src.push(" mat3 tsn = mat3( S, T, N );");// src.push(" mapN *= 3.0;"); src.push(" return normalize( tsn * mapN );");src.push("}");src.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {");src.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );");src.push("}");// STRUCTURES @@ -14969,8 +14972,8 @@ src.push("};");// IRRADIANCE EVALUATION src.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {");src.push(" float r = ggxRoughness + 0.0001;");src.push(" return (2.0 / (r * r) - 2.0);");src.push("}");src.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {");src.push(" float maxMIPLevelScalar = float( maxMIPLevel );");src.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );");src.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );");src.push("}");if(lightsState.reflectionMaps.length>0){src.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {");src.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);");//TODO: a random factor - fix this src.push(" vec3 envMapColor = "+TEXTURE_DECODE_FUNCS[lightsState.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;");src.push(" return envMapColor;");src.push("}");}// SPECULAR BRDF EVALUATION src.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {");src.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );");src.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;");src.push("}");src.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );");src.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );");src.push(" return 1.0 / ( gl * gv );");src.push("}");src.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );");src.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );");src.push(" return 0.5 / max( gv + gl, EPSILON );");src.push("}");src.push("float D_GGX(const in float alpha, const in float dotNH) {");src.push(" float a2 = ( alpha * alpha );");src.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;");src.push(" return RECIPROCAL_PI * a2 / ( denom * denom);");src.push("}");src.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {");src.push(" float alpha = ( roughness * roughness );");src.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );");src.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );");src.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );");src.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );");src.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );");src.push(" vec3 F = F_Schlick( specularColor, dotLH );");src.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );");src.push(" float D = D_GGX( alpha, dotNH );");src.push(" return F * (G * D);");src.push("}");src.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {");src.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));");src.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);");src.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);");src.push(" vec4 r = roughness * c0 + c1;");src.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;");src.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;");src.push(" return specularColor * AB.x + AB.y;");src.push("}");if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");if(lightsState.lightMaps.length>0){src.push(" vec3 irradiance = "+TEXTURE_DECODE_FUNCS[lightsState.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;");src.push(" irradiance *= PI;");src.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;");}if(lightsState.reflectionMaps.length>0){src.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);");src.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);");src.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);");src.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);");src.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);");src.push(" reflectedLight.specular += radiance * specularBRDFContrib;");}src.push("}");}// MAIN LIGHTING COMPUTATION FUNCTION -src.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");src.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));");src.push(" vec3 irradiance = dotNL * incidentLight.color * PI;");src.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);");src.push("}");src.push("out vec4 outColor;");src.push("void main(void) {");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i235=0,_len52=sectionPlanesState.getNumAllocatedSectionPlanes();_i235<_len52;_i235++){src.push("if (sectionPlaneActive"+_i235+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i235+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i235+".xyz), 0.0, 1000.0);");src.push("}");}if(clippingCaps){src.push(" if (dist > (0.002 * vClipPosition.w)) {");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);");if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" return;");src.push("}");}else{src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");}src.push("}");}src.push("IncidentLight light;");src.push("Material material;");src.push("Geometry geometry;");src.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));");src.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));");src.push("float opacity = float(vColor.a) / 255.0;");src.push("vec3 baseColor = rgb;");src.push("float specularF0 = 1.0;");src.push("float metallic = float(vMetallicRoughness.r) / 255.0;");src.push("float roughness = float(vMetallicRoughness.g) / 255.0;");src.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;");src.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));");src.push("baseColor *= colorTexel.rgb;");// src.push("opacity = colorTexel.a;"); -src.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;");src.push("metallic *= metalRoughTexel.b;");src.push("roughness *= metalRoughTexel.g;");src.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );");src.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);");src.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);");src.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);");src.push("geometry.position = vViewPosition.xyz;");src.push("geometry.viewNormal = -normalize(viewNormal);");src.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);");if(lightsState.lightMaps.length>0){src.push("geometry.worldNormal = normalize(vWorldNormal);");}if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("computePBRLightMapping(geometry, material, reflectedLight);");}for(var _i236=0,_len53=lightsState.lights.length;_i236<_len53;_i236++){var _light8=lightsState.lights[_i236];if(_light8.type==="ambient"){continue;}if(_light8.type==="dir"){if(_light8.space==="view"){src.push("light.direction = normalize(lightDir"+_i236+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i236+", 0.0)).xyz);");}}else if(_light8.type==="point"){if(_light8.space==="view"){src.push("light.direction = normalize(lightPos"+_i236+" - vViewPosition.xyz);");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightPos"+_i236+", 0.0)).xyz);");}}else if(_light8.type==="spot"){if(_light8.space==="view"){src.push("light.direction = normalize(lightDir"+_i236+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i236+", 0.0)).xyz);");}}else{continue;}src.push("light.color = lightColor"+_i236+".rgb * lightColor"+_i236+".a;");// a is intensity +src.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {");src.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));");src.push(" vec3 irradiance = dotNL * incidentLight.color * PI;");src.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);");src.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);");src.push("}");src.push("out vec4 outColor;");src.push("void main(void) {");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i237=0,_len52=sectionPlanesState.getNumAllocatedSectionPlanes();_i237<_len52;_i237++){src.push("if (sectionPlaneActive"+_i237+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i237+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i237+".xyz), 0.0, 1000.0);");src.push("}");}if(clippingCaps){src.push(" if (dist > (0.002 * vClipPosition.w)) {");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);");if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" return;");src.push("}");}else{src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");}src.push("}");}src.push("IncidentLight light;");src.push("Material material;");src.push("Geometry geometry;");src.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));");src.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));");src.push("float opacity = float(vColor.a) / 255.0;");src.push("vec3 baseColor = rgb;");src.push("float specularF0 = 1.0;");src.push("float metallic = float(vMetallicRoughness.r) / 255.0;");src.push("float roughness = float(vMetallicRoughness.g) / 255.0;");src.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;");src.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));");src.push("baseColor *= colorTexel.rgb;");// src.push("opacity = colorTexel.a;"); +src.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;");src.push("metallic *= metalRoughTexel.b;");src.push("roughness *= metalRoughTexel.g;");src.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );");src.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);");src.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);");src.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);");src.push("geometry.position = vViewPosition.xyz;");src.push("geometry.viewNormal = -normalize(viewNormal);");src.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);");if(lightsState.lightMaps.length>0){src.push("geometry.worldNormal = normalize(vWorldNormal);");}if(lightsState.lightMaps.length>0||lightsState.reflectionMaps.length>0){src.push("computePBRLightMapping(geometry, material, reflectedLight);");}for(var _i238=0,_len53=lightsState.lights.length;_i238<_len53;_i238++){var _light8=lightsState.lights[_i238];if(_light8.type==="ambient"){continue;}if(_light8.type==="dir"){if(_light8.space==="view"){src.push("light.direction = normalize(lightDir"+_i238+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i238+", 0.0)).xyz);");}}else if(_light8.type==="point"){if(_light8.space==="view"){src.push("light.direction = normalize(lightPos"+_i238+" - vViewPosition.xyz);");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightPos"+_i238+", 0.0)).xyz);");}}else if(_light8.type==="spot"){if(_light8.space==="view"){src.push("light.direction = normalize(lightDir"+_i238+");");}else{src.push("light.direction = normalize((viewMatrix * vec4(lightDir"+_i238+", 0.0)).xyz);");}}else{continue;}src.push("light.color = lightColor"+_i238+".rgb * lightColor"+_i238+".a;");// a is intensity src.push("computePBRLighting(light, geometry, material, reflectedLight);");}src.push("vec3 emissiveColor = sRGBToLinear(texture(uEmissiveMap, vUV)).rgb;");// TODO: correct gamma function src.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * baseColor * opacity * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular) + emissiveColor;");src.push("vec4 fragColor;");if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject @@ -14980,14 +14983,14 @@ src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewp src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src,3);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out float vFlags;");}src.push("out vec4 vWorldPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vFlags = flags;");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("in float vFlags;");for(var _i237=0;_i237> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsFlatRenderer;}(TrianglesInstancingRenderer);/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vFlags = flags;");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("in float vFlags;");for(var _i239=0;_i239> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}}]);return TrianglesPickNormalsFlatRenderer;}(TrianglesInstancingRenderer);/** * @private */var TrianglesColorTextureRenderer=/*#__PURE__*/function(_TrianglesInstancingR14){_inherits(TrianglesColorTextureRenderer,_TrianglesInstancingR14);var _super82=_createSuper(TrianglesColorTextureRenderer);function TrianglesColorTextureRenderer(){_classCallCheck(this,TrianglesColorTextureRenderer);return _super82.apply(this,arguments);}_createClass(TrianglesColorTextureRenderer,[{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene.gammaOutput,scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(TrianglesColorTextureRenderer.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry drawing vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");src.push("in vec2 uv;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);src.push("uniform mat3 uvDecodeMatrix;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("out vec4 vColor;");src.push("out vec2 vUV;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE | COLOR_TRANSPARENT src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vViewPosition = viewPosition;");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");src.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var gammaOutput=scene.gammaOutput;// If set, then it expects that all textures and colors need to be outputted in premultiplied gamma. Default is false. -var sectionPlanesState=scene._sectionPlanesState;var lightsState=scene._lightsState;var i;var len;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}src.push("uniform float gammaFactor;");src.push("vec4 linearToLinear( in vec4 value ) {");src.push(" return value;");src.push("}");src.push("vec4 sRGBToLinear( in vec4 value ) {");src.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 );");src.push("}");src.push("vec4 gammaToLinear( in vec4 value) {");src.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );");src.push("}");if(gammaOutput){src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i238=0,_len54=sectionPlanesState.getNumAllocatedSectionPlanes();_i238<_len54;_i238++){src.push("uniform bool sectionPlaneActive"+_i238+";");src.push("uniform vec3 sectionPlanePos"+_i238+";");src.push("uniform vec3 sectionPlaneDir"+_i238+";");}src.push("uniform float sliceThickness;");src.push("uniform vec4 sliceColor;");}this._addMatricesUniformBlockLines(src);src.push("uniform vec4 lightAmbient;");for(i=0,len=lightsState.lights.length;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i239=0,_len55=sectionPlanesState.getNumAllocatedSectionPlanes();_i239<_len55;_i239++){src.push("if (sectionPlaneActive"+_i239+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i239+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i239+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(i=0,len=lightsState.lights.length;i0;var src=[];src.push("#version 300 es");src.push("// Instancing geometry drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform sampler2D uColorMap;");if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}src.push("uniform float gammaFactor;");src.push("vec4 linearToLinear( in vec4 value ) {");src.push(" return value;");src.push("}");src.push("vec4 sRGBToLinear( in vec4 value ) {");src.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 );");src.push("}");src.push("vec4 gammaToLinear( in vec4 value) {");src.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );");src.push("}");if(gammaOutput){src.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {");src.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i240=0,_len54=sectionPlanesState.getNumAllocatedSectionPlanes();_i240<_len54;_i240++){src.push("uniform bool sectionPlaneActive"+_i240+";");src.push("uniform vec3 sectionPlanePos"+_i240+";");src.push("uniform vec3 sectionPlaneDir"+_i240+";");}src.push("uniform float sliceThickness;");src.push("uniform vec4 sliceColor;");}this._addMatricesUniformBlockLines(src);src.push("uniform vec4 lightAmbient;");for(i=0,len=lightsState.lights.length;i> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i241=0,_len55=sectionPlanesState.getNumAllocatedSectionPlanes();_i241<_len55;_i241++){src.push("if (sectionPlaneActive"+_i241+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i241+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i241+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > sliceThickness) { ");src.push(" discard;");src.push(" }");src.push(" if (dist > 0.0) { ");src.push(" newColor = sliceColor;");src.push(" }");src.push("}");}src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");src.push("vec3 xTangent = dFdx( vViewPosition.xyz );");src.push("vec3 yTangent = dFdy( vViewPosition.xyz );");src.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(i=0,len=lightsState.lights.length;i> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i240=0;_i240> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i241=0;_i241 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapInitRenderer;}(VBORenderer);var tempVec3a$x=math.vec3();var tempVec3b$t=math.vec3();var tempVec3c$o=math.vec3();var tempVec3d$8=math.vec3();var tempMat4a$n=math.mat4();/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i242=0;_i242> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i243=0;_i243 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapInitRenderer;}(VBORenderer);var tempVec3a$x=math.vec3();var tempVec3b$t=math.vec3();var tempVec3c$o=math.vec3();var tempVec3d$8=math.vec3();var tempMat4a$n=math.mat4();/** * @private */var TrianglesSnapRenderer=/*#__PURE__*/function(_VBORenderer6){_inherits(TrianglesSnapRenderer,_VBORenderer6);var _super84=_createSuper(TrianglesSnapRenderer);function TrianglesSnapRenderer(scene){_classCallCheck(this,TrianglesSnapRenderer);return _super84.call(this,scene,false,{instancing:true});}_createClass(TrianglesSnapRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,instancingLayer,renderPass){if(!this._program){this._allocate(instancingLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=instancingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=instancingLayer._state;var origin=instancingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=instancingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(instancingLayer)){gl.bindVertexArray(this._vaoCache.get(instancingLayer));}else{this._vaoCache.set(instancingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$x;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$t;if(origin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$o);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$n);rtcCameraEye=tempVec3d$8;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix @@ -15008,7 +15011,7 @@ src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.pu // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i242=0;_i242> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i243=0;_i243 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapRenderer;}(VBORenderer);/** +src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i244=0;_i244> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i245=0;_i245 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return TrianglesSnapRenderer;}(VBORenderer);/** * @private */var Renderers=/*#__PURE__*/function(){function Renderers(scene){_classCallCheck(this,Renderers);this._scene=scene;}_createClass(Renderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()){this._colorRendererWithSAO.destroy();this._colorRendererWithSAO=null;}if(this._flatColorRenderer&&!this._flatColorRenderer.getValid()){this._flatColorRenderer.destroy();this._flatColorRenderer=null;}if(this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()){this._flatColorRendererWithSAO.destroy();this._flatColorRendererWithSAO=null;}if(this._pbrRenderer&&!this._pbrRenderer.getValid()){this._pbrRenderer.destroy();this._pbrRenderer=null;}if(this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()){this._pbrRendererWithSAO.destroy();this._pbrRendererWithSAO=null;}if(this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()){this._colorTextureRenderer.destroy();this._colorTextureRenderer=null;}if(this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()){this._colorTextureRendererWithSAO.destroy();this._colorTextureRendererWithSAO=null;}if(this._depthRenderer&&!this._depthRenderer.getValid()){this._depthRenderer.destroy();this._depthRenderer=null;}if(this._normalsRenderer&&!this._normalsRenderer.getValid()){this._normalsRenderer.destroy();this._normalsRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._edgesRenderer&&!this._edgesRenderer.getValid()){this._edgesRenderer.destroy();this._edgesRenderer=null;}if(this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()){this._edgesColorRenderer.destroy();this._edgesColorRenderer=null;}if(this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()){this._pickMeshRenderer.destroy();this._pickMeshRenderer=null;}if(this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()){this._pickDepthRenderer.destroy();this._pickDepthRenderer=null;}if(this._pickNormalsRenderer&&this._pickNormalsRenderer.getValid()===false){this._pickNormalsRenderer.destroy();this._pickNormalsRenderer=null;}if(this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()){this._pickNormalsFlatRenderer.destroy();this._pickNormalsFlatRenderer=null;}if(this._occlusionRenderer&&this._occlusionRenderer.getValid()===false){this._occlusionRenderer.destroy();this._occlusionRenderer=null;}if(this._shadowRenderer&&!this._shadowRenderer.getValid()){this._shadowRenderer.destroy();this._shadowRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"eagerCreateRenders",value:function eagerCreateRenders(){// Pre-initialize certain renderers that would otherwise be lazy-initialised // on user interaction, such as picking or emphasis, so that there is no delay @@ -15046,7 +15049,7 @@ this._modelNormalMatrixCol0=[];this._modelNormalMatrixCol1=[];this._modelNormalM */this.solid=!!cfg.solid;/** * The number of indices in this layer. * @type {number|*} - */this.numIndices=cfg.geometry.numIndices;}_createClass(VBOInstancingTrianglesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i244=0,len=this._meshes.length;_i244 RTC -rtcRayDir.set(worldRayDir);if(offset){math.subVec3(rtcRayOrigin,offset);}math.transformRay(this.model.worldNormalMatrix,rtcRayOrigin,rtcRayDir,rtcRayOrigin,rtcRayDir);math.transformRay(portion.inverseMatrix,rtcRayOrigin,rtcRayDir,rtcRayOrigin,rtcRayDir);var a=tempVec3d$7;var b=tempVec3e;var c=tempVec3f;var gotIntersect=false;var closestDist=0;var closestIntersectPos=tempVec3g;for(var _i246=0,len=indices.length;_i246closestDist){closestDist=dist;worldSurfacePos.set(closestIntersectPos);if(worldNormal){// Not that wasteful to eagerly compute - unlikely to hit >2 surfaces on most geometry +rtcRayDir.set(worldRayDir);if(offset){math.subVec3(rtcRayOrigin,offset);}math.transformRay(this.model.worldNormalMatrix,rtcRayOrigin,rtcRayDir,rtcRayOrigin,rtcRayDir);math.transformRay(portion.inverseMatrix,rtcRayOrigin,rtcRayDir,rtcRayOrigin,rtcRayDir);var a=tempVec3d$7;var b=tempVec3e;var c=tempVec3f;var gotIntersect=false;var closestDist=0;var closestIntersectPos=tempVec3g;for(var _i248=0,len=indices.length;_i248closestDist){closestDist=dist;worldSurfacePos.set(closestIntersectPos);if(worldNormal){// Not that wasteful to eagerly compute - unlikely to hit >2 surfaces on most geometry math.triangleNormal(a,b,c,worldNormal);}gotIntersect=true;}}}if(gotIntersect&&worldNormal){math.transformVec3(portion.normalMatrix,worldNormal,worldNormal);math.transformVec3(this.model.worldNormalMatrix,worldNormal,worldNormal);math.normalizeVec3(worldNormal);}return gotIntersect;}},{key:"destroy",value:function destroy(){var state=this._state;if(state.colorsBuf){state.colorsBuf.destroy();state.colorsBuf=null;}if(state.metallicRoughnessBuf){state.metallicRoughnessBuf.destroy();state.metallicRoughnessBuf=null;}if(state.flagsBuf){state.flagsBuf.destroy();state.flagsBuf=null;}if(state.offsetsBuf){state.offsetsBuf.destroy();state.offsetsBuf=null;}if(state.modelMatrixCol0Buf){state.modelMatrixCol0Buf.destroy();state.modelMatrixCol0Buf=null;}if(state.modelMatrixCol1Buf){state.modelMatrixCol1Buf.destroy();state.modelMatrixCol1Buf=null;}if(state.modelMatrixCol2Buf){state.modelMatrixCol2Buf.destroy();state.modelMatrixCol2Buf=null;}if(state.modelNormalMatrixCol0Buf){state.modelNormalMatrixCol0Buf.destroy();state.modelNormalMatrixCol0Buf=null;}if(state.modelNormalMatrixCol1Buf){state.modelNormalMatrixCol1Buf.destroy();state.modelNormalMatrixCol1Buf=null;}if(state.modelNormalMatrixCol2Buf){state.modelNormalMatrixCol2Buf.destroy();state.modelNormalMatrixCol2Buf=null;}if(state.pickColorsBuf){state.pickColorsBuf.destroy();state.pickColorsBuf=null;}state.destroy();this._state=null;}}]);return VBOInstancingTrianglesLayer;}();/** * @private */var VBOSceneModelLineBatchingRenderer=/*#__PURE__*/function(_VBORenderer7){_inherits(VBOSceneModelLineBatchingRenderer,_VBORenderer7);var _super85=_createSuper(VBOSceneModelLineBatchingRenderer);function VBOSceneModelLineBatchingRenderer(){_classCallCheck(this,VBOSceneModelLineBatchingRenderer);return _super85.apply(this,arguments);}_createClass(VBOSceneModelLineBatchingRenderer,[{key:"_draw",value:function _draw(drawCfg){var gl=this._scene.canvas.gl;var state=drawCfg.state,frameCtx=drawCfg.frameCtx,incrementDrawState=drawCfg.incrementDrawState;gl.drawElements(gl.LINES,state.indicesBuf.numItems,state.indicesBuf.itemType,0);if(incrementDrawState){frameCtx.drawElements++;}}}]);return VBOSceneModelLineBatchingRenderer;}(VBORenderer);/** @@ -15145,12 +15148,12 @@ math.triangleNormal(a,b,c,worldNormal);}gotIntersect=true;}}}if(gotIntersect&&wo */var VBOBatchingLinesColorRenderer=/*#__PURE__*/function(_VBOSceneModelLineBat){_inherits(VBOBatchingLinesColorRenderer,_VBOSceneModelLineBat);var _super86=_createSuper(VBOBatchingLinesColorRenderer);function VBOBatchingLinesColorRenderer(){_classCallCheck(this,VBOBatchingLinesColorRenderer);return _super86.apply(this,arguments);}_createClass(VBOBatchingLinesColorRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,layer,renderPass){_get(_getPrototypeOf(VBOBatchingLinesColorRenderer.prototype),"drawLayer",this).call(this,frameCtx,layer,renderPass,{incrementDrawState:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching color vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");src.push("in vec4 color;");src.push("in float flags;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}this._addMatricesUniformBlockLines(src);if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i247=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i247> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i248=0,_len56=sectionPlanesState.getNumAllocatedSectionPlanes();_i248<_len56;_i248++){src.push("if (sectionPlaneActive"+_i248+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i248+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i248+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOBatchingLinesColorRenderer;}(VBOSceneModelLineBatchingRenderer);/** +src.push("} else {");src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i249=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i249> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i250=0,_len56=sectionPlanesState.getNumAllocatedSectionPlanes();_i250<_len56;_i250++){src.push("if (sectionPlaneActive"+_i250+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i250+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i250+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOBatchingLinesColorRenderer;}(VBOSceneModelLineBatchingRenderer);/** * @private */var VBOBatchingLinesSilhouetteRenderer=/*#__PURE__*/function(_VBOSceneModelLineBat2){_inherits(VBOBatchingLinesSilhouetteRenderer,_VBOSceneModelLineBat2);var _super87=_createSuper(VBOBatchingLinesSilhouetteRenderer);function VBOBatchingLinesSilhouetteRenderer(){_classCallCheck(this,VBOBatchingLinesSilhouetteRenderer);return _super87.apply(this,arguments);}_createClass(VBOBatchingLinesSilhouetteRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){_get(_getPrototypeOf(VBOBatchingLinesSilhouetteRenderer.prototype),"drawLayer",this).call(this,frameCtx,batchingLayer,renderPass,{colorUniform:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching silhouette vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);src.push("uniform vec4 color;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// silhouetteFlag = NOT_RENDERED | SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED // renderPass = SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED src.push("int silhouetteFlag = int(flags) >> 4 & 0xF;");src.push("if (silhouetteFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i249=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i249> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i250=0,_len57=sectionPlanesState.getNumAllocatedSectionPlanes();_i250<_len57;_i250++){src.push("if (sectionPlaneActive"+_i250+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i250+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i250+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = color;");src.push("}");return src;}}]);return VBOBatchingLinesSilhouetteRenderer;}(VBOSceneModelLineBatchingRenderer);var tempVec3a$v=math.vec3();var tempVec3b$r=math.vec3();var tempVec3c$m=math.vec3();var tempVec3d$6=math.vec3();var tempMat4a$m=math.mat4();/** +src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines batching silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i251=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i251> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i252=0,_len57=sectionPlanesState.getNumAllocatedSectionPlanes();_i252<_len57;_i252++){src.push("if (sectionPlaneActive"+_i252+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i252+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i252+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = color;");src.push("}");return src;}}]);return VBOBatchingLinesSilhouetteRenderer;}(VBOSceneModelLineBatchingRenderer);var tempVec3a$v=math.vec3();var tempVec3b$r=math.vec3();var tempVec3c$m=math.vec3();var tempVec3d$6=math.vec3();var tempMat4a$m=math.mat4();/** * @private */var VBOBatchingLinesSnapInitRenderer=/*#__PURE__*/function(_VBORenderer8){_inherits(VBOBatchingLinesSnapInitRenderer,_VBORenderer8);var _super88=_createSuper(VBOBatchingLinesSnapInitRenderer);function VBOBatchingLinesSnapInitRenderer(){_classCallCheck(this,VBOBatchingLinesSnapInitRenderer);return _super88.apply(this,arguments);}_createClass(VBOBatchingLinesSnapInitRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=batchingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=batchingLayer._state;var origin=batchingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=batchingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(batchingLayer)){gl.bindVertexArray(this._vaoCache.get(batchingLayer));}else{this._vaoCache.set(batchingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$v;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$r;if(origin){var rotatedOrigin=tempVec3c$m;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$m);rtcCameraEye=tempVec3d$6;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix? @@ -15160,7 +15163,7 @@ gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}this.setSectionPlanesStateUnif state.indicesBuf.bind();gl.drawElements(gl.LINES,state.indicesBuf.numItems,state.indicesBuf.itemType,0);state.indicesBuf.unbind();}},{key:"_allocate",value:function _allocate(){_get(_getPrototypeOf(VBOBatchingLinesSnapInitRenderer.prototype),"_allocate",this).call(this);var program=this._program;{this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}this._uCameraEyeRtc=program.getLocation("uCameraEyeRtc");this.uVectorA=program.getLocation("snapVectorA");this.uInverseVectorAB=program.getLocation("snapInvVectorAB");this._uLayerNumber=program.getLocation("layerNumber");this._uCoordinateScaler=program.getLocation("coordinateScaler");}},{key:"_bindProgram",value:function _bindProgram(){this._program.bind();}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");src.push("in vec4 pickColor;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 snapVectorA;");src.push("uniform vec2 snapInvVectorAB;");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;");src.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i251=0;_i251> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingLinesSnapInitRenderer;}(VBORenderer);var tempVec3a$u=math.vec3();var tempVec3b$q=math.vec3();var tempVec3c$l=math.vec3();var tempVec3d$5=math.vec3();var tempMat4a$l=math.mat4();/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i253=0;_i253> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingLinesSnapInitRenderer;}(VBORenderer);var tempVec3a$u=math.vec3();var tempVec3b$q=math.vec3();var tempVec3c$l=math.vec3();var tempVec3d$5=math.vec3();var tempMat4a$l=math.mat4();/** * @private */var VBOBatchingLinesSnapRenderer=/*#__PURE__*/function(_VBORenderer9){_inherits(VBOBatchingLinesSnapRenderer,_VBORenderer9);var _super89=_createSuper(VBOBatchingLinesSnapRenderer);function VBOBatchingLinesSnapRenderer(){_classCallCheck(this,VBOBatchingLinesSnapRenderer);return _super89.apply(this,arguments);}_createClass(VBOBatchingLinesSnapRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=batchingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=batchingLayer._state;var origin=batchingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=batchingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(batchingLayer)){gl.bindVertexArray(this._vaoCache.get(batchingLayer));}else{this._vaoCache.set(batchingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$u;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$q;if(origin){var rotatedOrigin=tempVec3c$l;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$l);rtcCameraEye=tempVec3d$5;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix? @@ -15172,7 +15175,7 @@ if(frameCtx.snapMode==="edge"){state.indicesBuf.bind();gl.drawElements(gl.LINES, // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapBatchingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i252=0;_i252> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingLinesSnapRenderer;}(VBORenderer);/** +src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapBatchingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i254=0;_i254> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingLinesSnapRenderer;}(VBORenderer);/** * @private */var VBOBatchingLinesRenderers=/*#__PURE__*/function(){function VBOBatchingLinesRenderers(scene){_classCallCheck(this,VBOBatchingLinesRenderers);this._scene=scene;}_createClass(VBOBatchingLinesRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"colorRenderer",get:function get(){if(!this._colorRenderer){this._colorRenderer=new VBOBatchingLinesColorRenderer(this._scene,false);}return this._colorRenderer;}},{key:"silhouetteRenderer",get:function get(){if(!this._silhouetteRenderer){this._silhouetteRenderer=new VBOBatchingLinesSilhouetteRenderer(this._scene);}return this._silhouetteRenderer;}},{key:"snapInitRenderer",get:function get(){if(!this._snapInitRenderer){this._snapInitRenderer=new VBOBatchingLinesSnapInitRenderer(this._scene,false);}return this._snapInitRenderer;}},{key:"snapRenderer",get:function get(){if(!this._snapRenderer){this._snapRenderer=new VBOBatchingLinesSnapRenderer(this._scene);}return this._snapRenderer;}},{key:"_destroy",value:function _destroy(){if(this._colorRenderer){this._colorRenderer.destroy();}if(this._silhouetteRenderer){this._silhouetteRenderer.destroy();}if(this._snapInitRenderer){this._snapInitRenderer.destroy();}if(this._snapRenderer){this._snapRenderer.destroy();}}}]);return VBOBatchingLinesRenderers;}();var cachedRenderers$4={};/** * @private @@ -15194,7 +15197,7 @@ this.positions=[];this.colors=[];this.offsets=[];this.indices=[];});/** * @type {Number} */this.layerIndex=cfg.layerIndex;this._renderers=getRenderers$5(cfg.model.scene);this.model=cfg.model;this._buffer=new VBOBatchingLinesBuffer(cfg.maxGeometryBatchSize);this._scratchMemory=cfg.scratchMemory;this._state=new RenderState({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:math.mat4(),origin:null});// These counts are used to avoid unnecessary render passes 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=math.collapseAABB3();// Model-space AABB -this._portions=[];this._meshes=[];this._numVerts=0;this._aabb=math.collapseAABB3();this.aabbDirty=true;this._finalized=false;if(cfg.positionsDecodeMatrix){this._state.positionsDecodeMatrix.set(cfg.positionsDecodeMatrix);this._preCompressedPositionsExpected=true;}else{this._preCompressedPositionsExpected=false;}if(cfg.origin){this._state.origin=math.vec3(cfg.origin);}}_createClass(VBOBatchingLinesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i253=0,len=this._meshes.length;_i2530){if(this._preCompressedPositionsExpected){var positions=new Uint16Array(buffer.positions);state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,positions,buffer.positions.length,3,gl.STATIC_DRAW);}else{var _positions2=new Float32Array(buffer.positions);var quantizedPositions=quantizePositions(_positions2,this._modelAABB,state.positionsDecodeMatrix);state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,quantizedPositions,buffer.positions.length,3,gl.STATIC_DRAW);}}if(buffer.colors.length>0){var colors=new Uint8Array(buffer.colors);var normalized=false;state.colorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,colors,buffer.colors.length,4,gl.DYNAMIC_DRAW,normalized);}if(buffer.colors.length>0){// Because we build flags arrays here, get their length from the colors array -var flagsLength=buffer.colors.length/4;var flags=new Float32Array(flagsLength);var notNormalized=false;state.flagsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,flags,flags.length,1,gl.DYNAMIC_DRAW,notNormalized);}if(this.model.scene.entityOffsetsEnabled){if(buffer.offsets.length>0){var offsets=new Float32Array(buffer.offsets);state.offsetsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,offsets,buffer.offsets.length,3,gl.DYNAMIC_DRAW);}}if(buffer.indices.length>0){var indices=new Uint32Array(buffer.indices);state.indicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,indices,buffer.indices.length,1,gl.STATIC_DRAW);}this._buffer=null;this._finalized=true;}},{key:"initFlags",value:function initFlags(portionId,flags,meshTransparent){if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}if(meshTransparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}var deferred=true;this._setFlags(portionId,flags,meshTransparent,deferred);}},{key:"flushInitFlags",value:function flushInitFlags(){this._setDeferredFlags();}},{key:"setVisible",value:function setVisible(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}else{this._numVisibleLayerPortions--;this.model.numVisibleLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setHighlighted",value:function setHighlighted(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}else{this._numHighlightedLayerPortions--;this.model.numHighlightedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setXRayed",value:function setXRayed(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}else{this._numXRayedLayerPortions--;this.model.numXRayedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setSelected",value:function setSelected(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}else{this._numSelectedLayerPortions--;this.model.numSelectedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setEdges",value:function setEdges(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}else{this._numEdgesLayerPortions--;this.model.numEdgesLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setClippable",value:function setClippable(portionId,flags){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}else{this._numClippableLayerPortions--;this.model.numClippableLayerPortions--;}this._setFlags(portionId,flags);}},{key:"setCulled",value:function setCulled(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}else{this._numCulledLayerPortions--;this.model.numCulledLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setCollidable",value:function setCollidable(portionId,flags){if(!this._finalized){throw"Not finalized";}}},{key:"setPickable",value:function setPickable(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}else{this._numPickableLayerPortions--;this.model.numPickableLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setColor",value:function setColor(portionId,color){if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId*2;var vertexBase=this._portions[portionsIdx];var numVerts=this._portions[portionsIdx+1];var firstColor=vertexBase*4;var lenColor=numVerts*4;var tempArray=this._scratchMemory.getUInt8Array(lenColor);var r=color[0];var g=color[1];var b=color[2];var a=color[3];for(var _i259=0;_i2590){var offsets=new Float32Array(buffer.offsets);state.offsetsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,offsets,buffer.offsets.length,3,gl.DYNAMIC_DRAW);}}if(buffer.indices.length>0){var indices=new Uint32Array(buffer.indices);state.indicesBuf=new ArrayBuf(gl,gl.ELEMENT_ARRAY_BUFFER,indices,buffer.indices.length,1,gl.STATIC_DRAW);}this._buffer=null;this._finalized=true;}},{key:"initFlags",value:function initFlags(portionId,flags,meshTransparent){if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}if(meshTransparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}var deferred=true;this._setFlags(portionId,flags,meshTransparent,deferred);}},{key:"flushInitFlags",value:function flushInitFlags(){this._setDeferredFlags();}},{key:"setVisible",value:function setVisible(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}else{this._numVisibleLayerPortions--;this.model.numVisibleLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setHighlighted",value:function setHighlighted(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}else{this._numHighlightedLayerPortions--;this.model.numHighlightedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setXRayed",value:function setXRayed(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}else{this._numXRayedLayerPortions--;this.model.numXRayedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setSelected",value:function setSelected(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}else{this._numSelectedLayerPortions--;this.model.numSelectedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setEdges",value:function setEdges(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.EDGES){this._numEdgesLayerPortions++;this.model.numEdgesLayerPortions++;}else{this._numEdgesLayerPortions--;this.model.numEdgesLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setClippable",value:function setClippable(portionId,flags){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}else{this._numClippableLayerPortions--;this.model.numClippableLayerPortions--;}this._setFlags(portionId,flags);}},{key:"setCulled",value:function setCulled(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}else{this._numCulledLayerPortions--;this.model.numCulledLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setCollidable",value:function setCollidable(portionId,flags){if(!this._finalized){throw"Not finalized";}}},{key:"setPickable",value:function setPickable(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}else{this._numPickableLayerPortions--;this.model.numPickableLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setColor",value:function setColor(portionId,color){if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId*2;var vertexBase=this._portions[portionsIdx];var numVerts=this._portions[portionsIdx+1];var firstColor=vertexBase*4;var lenColor=numVerts*4;var tempArray=this._scratchMemory.getUInt8Array(lenColor);var r=color[0];var g=color[1];var b=color[2];var a=color[3];for(var _i261=0;_i2613&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId*2;var vertexBase=this._portions[portionsIdx];var numVerts=this._portions[portionsIdx+1];var firstFlag=vertexBase;var lenFlags=numVerts;var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);// no edges var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);var colorFlag;if(!visible||culled||xrayed||highlighted&&!this.model.scene.highlightMaterial.glowThrough||selected&&!this.model.scene.selectedMaterial.glowThrough){colorFlag=RENDER_PASSES.NOT_RENDERED;}else{if(transparent){colorFlag=RENDER_PASSES.COLOR_TRANSPARENT;}else{colorFlag=RENDER_PASSES.COLOR_OPAQUE;}}var silhouetteFlag;if(!visible||culled){silhouetteFlag=RENDER_PASSES.NOT_RENDERED;}else if(selected){silhouetteFlag=RENDER_PASSES.SILHOUETTE_SELECTED;}else if(highlighted){silhouetteFlag=RENDER_PASSES.SILHOUETTE_HIGHLIGHTED;}else if(xrayed){silhouetteFlag=RENDER_PASSES.SILHOUETTE_XRAYED;}else{silhouetteFlag=RENDER_PASSES.NOT_RENDERED;}var pickFlag=visible&&!culled&&pickable?RENDER_PASSES.PICK:RENDER_PASSES.NOT_RENDERED;var clippableFlag=!!(flags&ENTITY_FLAGS.CLIPPABLE)?1:0;if(deferred){// Avoid zillions of individual WebGL bufferSubData calls - buffer them to apply in one shot -if(!this._deferredFlagValues){this._deferredFlagValues=new Float32Array(this._numVerts);}for(var _i260=firstFlag,len=firstFlag+lenFlags;_i260> 4 & 0xF;");src.push("if (silhouetteFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines instancing silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i263=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i263> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i264=0,_len60=sectionPlanesState.getNumAllocatedSectionPlanes();_i264<_len60;_i264++){src.push("if (sectionPlaneActive"+_i264+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i264+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i264+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = color;");src.push("}");return src;}}]);return VBOInstancingLinesSilhouetteRenderer;}(VBOInstancingLinesRenderer);var tempVec3a$t=math.vec3();var tempVec3b$p=math.vec3();var tempVec3c$k=math.vec3();math.vec3();var tempMat4a$k=math.mat4();/** +src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Lines instancing silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i265=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i265> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i266=0,_len60=sectionPlanesState.getNumAllocatedSectionPlanes();_i266<_len60;_i266++){src.push("if (sectionPlaneActive"+_i266+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i266+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i266+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = color;");src.push("}");return src;}}]);return VBOInstancingLinesSilhouetteRenderer;}(VBOInstancingLinesRenderer);var tempVec3a$t=math.vec3();var tempVec3b$p=math.vec3();var tempVec3c$k=math.vec3();math.vec3();var tempMat4a$k=math.mat4();/** * @private */var VBOInstancingLinesSnapInitRenderer=/*#__PURE__*/function(_VBORenderer11){_inherits(VBOInstancingLinesSnapInitRenderer,_VBORenderer11);var _super93=_createSuper(VBOInstancingLinesSnapInitRenderer);function VBOInstancingLinesSnapInitRenderer(scene){_classCallCheck(this,VBOInstancingLinesSnapInitRenderer);return _super93.call(this,scene,false,{instancing:true});}_createClass(VBOInstancingLinesSnapInitRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,instancingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=instancingLayer.model;var scene=model.scene;var gl=scene.canvas.gl;var camera=scene.camera;var state=instancingLayer._state;var origin=instancingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=instancingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(instancingLayer)){gl.bindVertexArray(this._vaoCache.get(instancingLayer));}else{this._vaoCache.set(instancingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$t;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$p;if(origin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$k);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$k);frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}this.setSectionPlanesStateUniforms(instancingLayer);this._aModelMatrixCol0.bindArrayBuffer(state.modelMatrixCol0Buf);this._aModelMatrixCol1.bindArrayBuffer(state.modelMatrixCol1Buf);this._aModelMatrixCol2.bindArrayBuffer(state.modelMatrixCol2Buf);gl.vertexAttribDivisor(this._aModelMatrixCol0.location,1);gl.vertexAttribDivisor(this._aModelMatrixCol1.location,1);gl.vertexAttribDivisor(this._aModelMatrixCol2.location,1);if(this._aFlags){this._aFlags.bindArrayBuffer(state.flagsBuf);gl.vertexAttribDivisor(this._aFlags.location,1);}state.indicesBuf.bind();gl.drawElementsInstanced(gl.LINES,state.indicesBuf.numItems,state.indicesBuf.itemType,0,state.numInstances);state.indicesBuf.unbind();// Cleanup @@ -15252,11 +15255,11 @@ gl.vertexAttribDivisor(this._aModelMatrixCol0.location,0);gl.vertexAttribDivisor src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);src.push("uniform vec2 snapVectorA;");src.push("uniform vec2 snapInvVectorAB;");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;");src.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i265=0;_i2650;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i267=0;_i267> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i266=0;_i266 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingLinesSnapInitRenderer;}(VBORenderer);var tempVec3a$s=math.vec3();var tempVec3b$o=math.vec3();var tempVec3c$j=math.vec3();math.vec3();var tempMat4a$j=math.mat4();/** +src.push("layout(location = 2) out lowp uvec4 outPickColor;");src.push("void main(void) {");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i268=0;_i268 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingLinesSnapInitRenderer;}(VBORenderer);var tempVec3a$s=math.vec3();var tempVec3b$o=math.vec3();var tempVec3c$j=math.vec3();math.vec3();var tempMat4a$j=math.mat4();/** * @private */var VBOInstancingLinesSnapRenderer=/*#__PURE__*/function(_VBORenderer12){_inherits(VBOInstancingLinesSnapRenderer,_VBORenderer12);var _super94=_createSuper(VBOInstancingLinesSnapRenderer);function VBOInstancingLinesSnapRenderer(scene){_classCallCheck(this,VBOInstancingLinesSnapRenderer);return _super94.call(this,scene,false,{instancing:true});}_createClass(VBOInstancingLinesSnapRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,instancingLayer,renderPass){if(!this._program){this._allocate(instancingLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=instancingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=instancingLayer._state;var origin=instancingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=instancingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(instancingLayer)){gl.bindVertexArray(this._vaoCache.get(instancingLayer));}else{this._vaoCache.set(instancingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$s;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$o;if(origin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$j);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$j);frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);// TODO: Far from pick project matrix @@ -15267,7 +15270,7 @@ src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.pu // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i267=0;_i267> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i268=0;_i268 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingLinesSnapRenderer;}(VBORenderer);/** +src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i269=0;_i269> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i270=0;_i270 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingLinesSnapRenderer;}(VBORenderer);/** * @private */var VBOInstancingLinesRenderers=/*#__PURE__*/function(){function VBOInstancingLinesRenderers(scene){_classCallCheck(this,VBOInstancingLinesRenderers);this._scene=scene;}_createClass(VBOInstancingLinesRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"eagerCreateRenders",value:function eagerCreateRenders(){// Pre-initialize renderers that would otherwise be lazy-initialised // on user interaction, such as picking or emphasis, so that there is no delay @@ -15321,7 +15324,7 @@ function getSnapInstancingRenderers(scene) { positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null});// These counts are used to avoid unnecessary render passes 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;/** @private */this.numIndices=cfg.geometry.numIndices;// Vertex arrays this._colors=[];this._offsets=[];// Modeling matrix per instance, array for each column -this._modelMatrixCol0=[];this._modelMatrixCol1=[];this._modelMatrixCol2=[];this._portions=[];this._meshes=[];this._aabb=math.collapseAABB3();this.aabbDirty=true;if(cfg.origin){this._state.origin=math.vec3(cfg.origin);}this._finalized=false;}_createClass(VBOInstancingLinesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i269=0,len=this._meshes.length;_i269 intensityRange[1]) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");}src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");if(pointsMaterial.filterIntensity){src.push("}");}src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i270=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i270 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i271=0,_len61=sectionPlanesState.getNumAllocatedSectionPlanes();_i271<_len61;_i271++){src.push("if (sectionPlaneActive"+_i271+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i271+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i271+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOBatchingPointsColorRenderer;}(VBOBatchingPointsRenderer);/** +src.push("} else {");}src.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push("worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");if(pointsMaterial.filterIntensity){src.push("}");}src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i272=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i272 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i273=0,_len61=sectionPlanesState.getNumAllocatedSectionPlanes();_i273<_len61;_i273++){src.push("if (sectionPlaneActive"+_i273+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i273+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i273+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOBatchingPointsColorRenderer;}(VBOBatchingPointsRenderer);/** * @private */var VBOBatchingPointsSilhouetteRenderer=/*#__PURE__*/function(_VBOBatchingPointsRen2){_inherits(VBOBatchingPointsSilhouetteRenderer,_VBOBatchingPointsRen2);var _super97=_createSuper(VBOBatchingPointsSilhouetteRenderer);function VBOBatchingPointsSilhouetteRenderer(){_classCallCheck(this,VBOBatchingPointsSilhouetteRenderer);return _super97.apply(this,arguments);}_createClass(VBOBatchingPointsSilhouetteRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"drawLayer",value:function drawLayer(frameCtx,pointsBatchingLayer,renderPass){_get(_getPrototypeOf(VBOBatchingPointsSilhouetteRenderer.prototype),"drawLayer",this).call(this,frameCtx,pointsBatchingLayer,renderPass,{colorUniform:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points batching silhouette vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);src.push("uniform vec4 color;");src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// silhouetteFlag = NOT_RENDERED | SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | SILHOUETTE_XRAYED // renderPass = SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED @@ -15373,19 +15376,19 @@ src.push("} else {");src.push(" vec4 worldPosition = worldMatrix * (positio */var VBOBatchingPointsPickMeshRenderer=/*#__PURE__*/function(_VBOBatchingPointsRen3){_inherits(VBOBatchingPointsPickMeshRenderer,_VBOBatchingPointsRen3);var _super98=_createSuper(VBOBatchingPointsPickMeshRenderer);function VBOBatchingPointsPickMeshRenderer(){_classCallCheck(this,VBOBatchingPointsPickMeshRenderer);return _super98.apply(this,arguments);}_createClass(VBOBatchingPointsPickMeshRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points batching pick mesh vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 pickColor;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vPickColor;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("gl_PointSize += 10.0;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching pick mesh vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i272=0;_i272 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vPickColor; ");src.push("}");return src;}}]);return VBOBatchingPointsPickMeshRenderer;}(VBOBatchingPointsRenderer);/** +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("gl_PointSize += 10.0;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching pick mesh vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var i=0;i 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i274=0;_i274 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vPickColor; ");src.push("}");return src;}}]);return VBOBatchingPointsPickMeshRenderer;}(VBOBatchingPointsRenderer);/** * @private */var VBOBatchingPointsPickDepthRenderer=/*#__PURE__*/function(_VBOBatchingPointsRen4){_inherits(VBOBatchingPointsPickDepthRenderer,_VBOBatchingPointsRen4);var _super99=_createSuper(VBOBatchingPointsPickDepthRenderer);function VBOBatchingPointsPickDepthRenderer(){_classCallCheck(this,VBOBatchingPointsPickDepthRenderer);return _super99.apply(this,arguments);}_createClass(VBOBatchingPointsPickDepthRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points batched pick depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("gl_PointSize += 10.0;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batched pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i273=0;_i273 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("gl_PointSize += 10.0;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batched pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i275=0;_i275 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth src.push("}");return src;}}]);return VBOBatchingPointsPickDepthRenderer;}(VBOBatchingPointsRenderer);/** * @private */var VBOBatchingPointsOcclusionRenderer=/*#__PURE__*/function(_VBOBatchingPointsRen5){_inherits(VBOBatchingPointsOcclusionRenderer,_VBOBatchingPointsRen5);var _super100=_createSuper(VBOBatchingPointsOcclusionRenderer);function VBOBatchingPointsOcclusionRenderer(){_classCallCheck(this,VBOBatchingPointsOcclusionRenderer);return _super100.apply(this,arguments);}_createClass(VBOBatchingPointsOcclusionRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points batching occlusion vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");this._addMatricesUniformBlockLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE // Only opaque objects can be occluders src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push(" gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching occlusion fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i274=0;_i274 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i275=0;_i275 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push(" gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points batching occlusion fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i276=0;_i276 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i277=0;_i277 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue src.push("}");return src;}}]);return VBOBatchingPointsOcclusionRenderer;}(VBOBatchingPointsRenderer);var tempVec3a$r=math.vec3();var tempVec3b$n=math.vec3();var tempVec3c$i=math.vec3();var tempVec3d$4=math.vec3();var tempMat4a$i=math.mat4();/** * @private */var VBOBatchingPointsSnapInitRenderer=/*#__PURE__*/function(_VBORenderer14){_inherits(VBOBatchingPointsSnapInitRenderer,_VBORenderer14);var _super101=_createSuper(VBOBatchingPointsSnapInitRenderer);function VBOBatchingPointsSnapInitRenderer(){_classCallCheck(this,VBOBatchingPointsSnapInitRenderer);return _super101.apply(this,arguments);}_createClass(VBOBatchingPointsSnapInitRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,batchingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=batchingLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=batchingLayer._state;var origin=batchingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=batchingLayer.aabb;// Per-layer AABB for best RTC accuracy @@ -15396,7 +15399,7 @@ gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}this.setSectionPlanesStateUnif gl.drawArrays(gl.POINTS,0,state.positionsBuf.numItems);}},{key:"_allocate",value:function _allocate(){_get(_getPrototypeOf(VBOBatchingPointsSnapInitRenderer.prototype),"_allocate",this).call(this);var program=this._program;{this._uLogDepthBufFC=program.getLocation("logDepthBufFC");}this._uCameraEyeRtc=program.getLocation("uCameraEyeRtc");this.uVectorA=program.getLocation("snapVectorA");this.uInverseVectorAB=program.getLocation("snapInvVectorAB");this._uLayerNumber=program.getLocation("layerNumber");this._uCoordinateScaler=program.getLocation("coordinateScaler");}},{key:"_bindProgram",value:function _bindProgram(){this._program.bind();}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBOBatchingPointsSnapInitRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");src.push("in vec4 pickColor;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 snapVectorA;");src.push("uniform vec2 snapInvVectorAB;");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;");src.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBOBatchingPointsSnapInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i276=0;_i276> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");// src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"); +src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBOBatchingPointsSnapInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i278=0;_i278> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");// src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"); // src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"); // src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"); src.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);");src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingPointsSnapInitRenderer;}(VBORenderer);var tempVec3a$q=math.vec3();var tempVec3b$m=math.vec3();var tempVec3c$h=math.vec3();var tempVec3d$3=math.vec3();var tempMat4a$h=math.mat4();/** @@ -15410,7 +15413,7 @@ gl.drawArrays(gl.POINTS,0,state.positionsBuf.numItems);}},{key:"_allocate",value // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBOBatchingPointsSnapRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i277=0;_i277> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingPointsSnapRenderer;}(VBORenderer);/** +src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// VBOBatchingPointsSnapRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i279=0;_i279> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOBatchingPointsSnapRenderer;}(VBORenderer);/** * @private */var VBOBatchingPointsRenderers=/*#__PURE__*/function(){function VBOBatchingPointsRenderers(scene){_classCallCheck(this,VBOBatchingPointsRenderers);this._scene=scene;}_createClass(VBOBatchingPointsRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()){this._pickMeshRenderer.destroy();this._pickMeshRenderer=null;}if(this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()){this._pickDepthRenderer.destroy();this._pickDepthRenderer=null;}if(this._occlusionRenderer&&this._occlusionRenderer.getValid()===false){this._occlusionRenderer.destroy();this._occlusionRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"colorRenderer",get:function get(){if(!this._colorRenderer){this._colorRenderer=new VBOBatchingPointsColorRenderer(this._scene);}return this._colorRenderer;}},{key:"silhouetteRenderer",get:function get(){if(!this._silhouetteRenderer){this._silhouetteRenderer=new VBOBatchingPointsSilhouetteRenderer(this._scene);}return this._silhouetteRenderer;}},{key:"pickMeshRenderer",get:function get(){if(!this._pickMeshRenderer){this._pickMeshRenderer=new VBOBatchingPointsPickMeshRenderer(this._scene);}return this._pickMeshRenderer;}},{key:"pickDepthRenderer",get:function get(){if(!this._pickDepthRenderer){this._pickDepthRenderer=new VBOBatchingPointsPickDepthRenderer(this._scene);}return this._pickDepthRenderer;}},{key:"occlusionRenderer",get:function get(){if(!this._occlusionRenderer){this._occlusionRenderer=new VBOBatchingPointsOcclusionRenderer(this._scene);}return this._occlusionRenderer;}},{key:"snapInitRenderer",get:function get(){if(!this._snapInitRenderer){this._snapInitRenderer=new VBOBatchingPointsSnapInitRenderer(this._scene,false);}return this._snapInitRenderer;}},{key:"snapRenderer",get:function get(){if(!this._snapRenderer){this._snapRenderer=new VBOBatchingPointsSnapRenderer(this._scene);}return this._snapRenderer;}},{key:"_destroy",value:function _destroy(){if(this._colorRenderer){this._colorRenderer.destroy();}if(this._silhouetteRenderer){this._silhouetteRenderer.destroy();}if(this._pickMeshRenderer){this._pickMeshRenderer.destroy();}if(this._pickDepthRenderer){this._pickDepthRenderer.destroy();}if(this._occlusionRenderer){this._occlusionRenderer.destroy();}if(this._snapInitRenderer){this._snapInitRenderer.destroy();}if(this._snapRenderer){this._snapRenderer.destroy();}}}]);return VBOBatchingPointsRenderers;}();var cachedRenderers$2={};/** * @private @@ -15438,7 +15441,7 @@ this.positions=[];this.colors=[];this.intensities=[];this.pickColors=[];this.off * @type {Number} */this.layerIndex=cfg.layerIndex;this._renderers=getRenderers$3(cfg.model.scene);this._buffer=new VBOBatchingPointsBuffer(cfg.maxGeometryBatchSize);this._scratchMemory=cfg.scratchMemory;this._state=new RenderState({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:math.mat4(),origin:null});// These counts are used to avoid unnecessary render passes 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=math.collapseAABB3();// Model-space AABB -this._portions=[];this._meshes=[];this._aabb=math.collapseAABB3();this.aabbDirty=true;this._finalized=false;if(cfg.positionsDecodeMatrix){this._state.positionsDecodeMatrix.set(cfg.positionsDecodeMatrix);this._preCompressedPositionsExpected=true;}else{this._preCompressedPositionsExpected=false;}if(cfg.origin){this._state.origin=math.vec3(cfg.origin);}}_createClass(VBOBatchingPointsLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i278=0,len=this._meshes.length;_i2780){if(this._preCompressedPositionsExpected){var positions=new Uint16Array(buffer.positions);state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,positions,buffer.positions.length,3,gl.STATIC_DRAW);}else{var _positions3=new Float32Array(buffer.positions);var quantizedPositions=quantizePositions(_positions3,this._modelAABB,state.positionsDecodeMatrix);state.positionsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,quantizedPositions,buffer.positions.length,3,gl.STATIC_DRAW);}}if(buffer.colors.length>0){var colors=new Uint8Array(buffer.colors);var normalized=false;state.colorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,colors,buffer.colors.length,4,gl.STATIC_DRAW,normalized);}if(buffer.positions.length>0){// Because we build flags arrays here, get their length from the positions array var flagsLength=buffer.positions.length/3;var flags=new Float32Array(flagsLength);var notNormalized=false;state.flagsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,flags,flags.length,1,gl.DYNAMIC_DRAW,notNormalized);}if(buffer.pickColors.length>0){var pickColors=new Uint8Array(buffer.pickColors);var _normalized8=false;state.pickColorsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,pickColors,buffer.pickColors.length,4,gl.STATIC_DRAW,_normalized8);}if(this.model.scene.entityOffsetsEnabled){if(buffer.offsets.length>0){var offsets=new Float32Array(buffer.offsets);state.offsetsBuf=new ArrayBuf(gl,gl.ARRAY_BUFFER,offsets,buffer.offsets.length,3,gl.DYNAMIC_DRAW);}}this._buffer=null;this._finalized=true;}},{key:"initFlags",value:function initFlags(portionId,flags,meshTransparent){if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}if(meshTransparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}this._setFlags(portionId,flags,meshTransparent);}},{key:"setVisible",value:function setVisible(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.VISIBLE){this._numVisibleLayerPortions++;this.model.numVisibleLayerPortions++;}else{this._numVisibleLayerPortions--;this.model.numVisibleLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setHighlighted",value:function setHighlighted(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.HIGHLIGHTED){this._numHighlightedLayerPortions++;this.model.numHighlightedLayerPortions++;}else{this._numHighlightedLayerPortions--;this.model.numHighlightedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setXRayed",value:function setXRayed(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.XRAYED){this._numXRayedLayerPortions++;this.model.numXRayedLayerPortions++;}else{this._numXRayedLayerPortions--;this.model.numXRayedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setSelected",value:function setSelected(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.SELECTED){this._numSelectedLayerPortions++;this.model.numSelectedLayerPortions++;}else{this._numSelectedLayerPortions--;this.model.numSelectedLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setEdges",value:function setEdges(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}// Not applicable to point clouds -}},{key:"setClippable",value:function setClippable(portionId,flags){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CLIPPABLE){this._numClippableLayerPortions++;this.model.numClippableLayerPortions++;}else{this._numClippableLayerPortions--;this.model.numClippableLayerPortions--;}this._setFlags(portionId,flags);}},{key:"setCulled",value:function setCulled(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.CULLED){this._numCulledLayerPortions++;this.model.numCulledLayerPortions++;}else{this._numCulledLayerPortions--;this.model.numCulledLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setCollidable",value:function setCollidable(portionId,flags){if(!this._finalized){throw"Not finalized";}}},{key:"setPickable",value:function setPickable(portionId,flags,transparent){if(!this._finalized){throw"Not finalized";}if(flags&ENTITY_FLAGS.PICKABLE){this._numPickableLayerPortions++;this.model.numPickableLayerPortions++;}else{this._numPickableLayerPortions--;this.model.numPickableLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"setColor",value:function setColor(portionId,color){if(!this._finalized){throw"Not finalized";}var portionsIdx=portionId*2;var vertexBase=this._portions[portionsIdx];var numVerts=this._portions[portionsIdx+1];var firstColor=vertexBase*4;var lenColor=numVerts*4;var tempArray=this._scratchMemory.getUInt8Array(lenColor);var r=color[0];var g=color[1];var b=color[2];for(var _i286=0;_i286 intensityRange[1]) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");}src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");if(pointsMaterial.filterIntensity){src.push("}");}src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i289=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i289 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i290=0,_len66=sectionPlanesState.getNumAllocatedSectionPlanes();_i290<_len66;_i290++){src.push("if (sectionPlaneActive"+_i290+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i290+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i290+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOInstancingPointsColorRenderer;}(VBOInstancingPointsRenderer);/** +src.push("} else {");}src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");if(pointsMaterial.filterIntensity){src.push("}");}src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing color fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i291=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i291 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i292=0,_len66=sectionPlanesState.getNumAllocatedSectionPlanes();_i292<_len66;_i292++){src.push("if (sectionPlaneActive"+_i292+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i292+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i292+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}src.push(" outColor = vColor;");if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOInstancingPointsColorRenderer;}(VBOInstancingPointsRenderer);/** * @private */var VBOInstancingPointsSilhouetteRenderer=/*#__PURE__*/function(_VBOInstancingPointsR2){_inherits(VBOInstancingPointsSilhouetteRenderer,_VBOInstancingPointsR2);var _super105=_createSuper(VBOInstancingPointsSilhouetteRenderer);function VBOInstancingPointsSilhouetteRenderer(){_classCallCheck(this,VBOInstancingPointsSilhouetteRenderer);return _super105.apply(this,arguments);}_createClass(VBOInstancingPointsSilhouetteRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"drawLayer",value:function drawLayer(frameCtx,instancingLayer,renderPass){_get(_getPrototypeOf(VBOInstancingPointsSilhouetteRenderer.prototype),"drawLayer",this).call(this,frameCtx,instancingLayer,renderPass,{colorUniform:true});}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points instancing silhouette vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 color;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}src.push("uniform vec4 silhouetteColor;");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vColor;");src.push("void main(void) {");// silhouetteFlag = NOT_RENDERED | SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED // renderPass = SILHOUETTE_HIGHLIGHTED | SILHOUETTE_SELECTED | | SILHOUETTE_XRAYED src.push("int silhouetteFlag = int(flags) >> 4 & 0xF;");src.push("if (silhouetteFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);");src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i291=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i291 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i292=0,_len67=sectionPlanesState.getNumAllocatedSectionPlanes();_i292<_len67;_i292++){src.push("if (sectionPlaneActive"+_i292+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i292+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i292+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return VBOInstancingPointsSilhouetteRenderer;}(VBOInstancingPointsRenderer);/** +src.push("} else {");src.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);");src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing silhouette fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i293=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i293 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i294=0,_len67=sectionPlanesState.getNumAllocatedSectionPlanes();_i294<_len67;_i294++){src.push("if (sectionPlaneActive"+_i294+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i294+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i294+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vColor;");src.push("}");return src;}}]);return VBOInstancingPointsSilhouetteRenderer;}(VBOInstancingPointsRenderer);/** * @private */var VBOInstancingPointsPickMeshRenderer=/*#__PURE__*/function(_VBOInstancingPointsR3){_inherits(VBOInstancingPointsPickMeshRenderer,_VBOInstancingPointsR3);var _super106=_createSuper(VBOInstancingPointsPickMeshRenderer);function VBOInstancingPointsPickMeshRenderer(){_classCallCheck(this,VBOInstancingPointsPickMeshRenderer);return _super106.apply(this,arguments);}_createClass(VBOInstancingPointsPickMeshRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points instancing pick mesh vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 pickColor;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vPickColor;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = remapClipPos(clipPos);");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick mesh fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i293=0;_i293 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i294=0;_i294 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vPickColor; ");src.push("}");return src;}}]);return VBOInstancingPointsPickMeshRenderer;}(VBOInstancingPointsRenderer);/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = remapClipPos(clipPos);");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick mesh fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i295=0;_i295 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i296=0;_i296 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outColor = vPickColor; ");src.push("}");return src;}}]);return VBOInstancingPointsPickMeshRenderer;}(VBOInstancingPointsRenderer);/** * @private */var VBOInstancingPointsPickDepthRenderer=/*#__PURE__*/function(_VBOInstancingPointsR4){_inherits(VBOInstancingPointsPickDepthRenderer,_VBOInstancingPointsR4);var _super107=_createSuper(VBOInstancingPointsPickDepthRenderer);function VBOInstancingPointsPickDepthRenderer(){_classCallCheck(this,VBOInstancingPointsPickDepthRenderer);return _super107.apply(this,arguments);}_createClass(VBOInstancingPointsPickDepthRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);this._addRemapClipPosLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("out vec4 vViewPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = remapClipPos(clipPos);");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i295=0;_i295 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i296=0;_i296 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push(" vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("gl_Position = remapClipPos(clipPos);");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = remapClipPos(clipPos);");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform float pickZNear;");src.push("uniform float pickZFar;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i297=0;_i297 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i298=0;_i298 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));");src.push(" outColor = packDepth(zNormalizedDepth); ");// Must be linear depth src.push("}");return src;}}]);return VBOInstancingPointsPickDepthRenderer;}(VBOInstancingPointsRenderer);/** * @private */var VBOInstancingPointsOcclusionRenderer=/*#__PURE__*/function(_VBOInstancingPointsR5){_inherits(VBOInstancingPointsOcclusionRenderer,_VBOInstancingPointsR5);var _super108=_createSuper(VBOInstancingPointsOcclusionRenderer);function VBOInstancingPointsOcclusionRenderer(){_classCallCheck(this,VBOInstancingPointsOcclusionRenderer);return _super108.apply(this,arguments);}_createClass(VBOInstancingPointsOcclusionRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points instancing occlusion vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");// Modeling matrix src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE -src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing occlusion vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i297=0;_i297 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i298=0;_i298 0.0) { discard; }");src.push("}");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue +src.push("int colorFlag = int(flags) & 0xF;");src.push("if (colorFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");}src.push("gl_Position = clipPos;");if(pointsMaterial.perspectivePoints){src.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;");src.push("gl_PointSize = max(gl_PointSize, "+Math.floor(pointsMaterial.minPerspectivePointSize)+".0);");src.push("gl_PointSize = min(gl_PointSize, "+Math.floor(pointsMaterial.maxPerspectivePointSize)+".0);");}else{src.push("gl_PointSize = pointSize;");}src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing occlusion vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i299=0;_i299 1.0) {");src.push(" discard;");src.push(" }");}if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i300=0;_i300 0.0) { discard; }");src.push("}");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("}");return src;}}]);return VBOInstancingPointsOcclusionRenderer;}(VBOInstancingPointsRenderer);/** * @private */var VBOInstancingPointsDepthRenderer=/*#__PURE__*/function(_VBOInstancingPointsR6){_inherits(VBOInstancingPointsDepthRenderer,_VBOInstancingPointsR6);var _super109=_createSuper(VBOInstancingPointsDepthRenderer);function VBOInstancingPointsDepthRenderer(){_classCallCheck(this,VBOInstancingPointsDepthRenderer);return _super109.apply(this,arguments);}_createClass(VBOInstancingPointsDepthRenderer,[{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash;}},{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var pointsMaterial=scene.pointsMaterial._state;var src=[];src.push('#version 300 es');src.push("// Points instancing depth vertex shader");src.push("uniform int renderPass;");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");this._addMatricesUniformBlockLines(src);src.push("uniform float pointSize;");if(pointsMaterial.perspectivePoints){src.push("uniform float nearPlaneHeight;");}if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");// colorFlag = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT @@ -15520,7 +15523,7 @@ if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDept * * @private */var VBOInstancingPointsShadowRenderer=/*#__PURE__*/function(_VBOInstancingPointsR7){_inherits(VBOInstancingPointsShadowRenderer,_VBOInstancingPointsR7);var _super110=_createSuper(VBOInstancingPointsShadowRenderer);function VBOInstancingPointsShadowRenderer(){_classCallCheck(this,VBOInstancingPointsShadowRenderer);return _super110.apply(this,arguments);}_createClass(VBOInstancingPointsShadowRenderer,[{key:"_buildVertexShader",value:function _buildVertexShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Instancing geometry shadow drawing vertex shader");src.push("in vec3 position;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("in vec4 color;");src.push("in float flags;");src.push("in vec4 modelMatrixCol0;");src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform mat4 shadowViewMatrix;");src.push("uniform mat4 shadowProjMatrix;");this._addMatricesUniformBlockLines(src);src.push("uniform float pointSize;");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out float vFlags;");}src.push("void main(void) {");src.push("int colorFlag = int(flags) & 0xF;");src.push("bool visible = (colorFlag > 0);");src.push("bool transparent = ((float(color.a) / 255.0) < 1.0);");src.push("if (!visible || transparent) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push("}");src.push("gl_PointSize = pointSize;");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i299=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i299 1.0) {");src.push(" discard;");src.push(" }");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i300=0,_len68=sectionPlanesState.getNumAllocatedSectionPlanes();_i300<_len68;_i300++){src.push("if (sectionPlaneActive"+_i300+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i300+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i300+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return VBOInstancingPointsShadowRenderer;}(VBOInstancingPointsRenderer);var tempVec3a$p=math.vec3();var tempVec3b$l=math.vec3();var tempVec3c$g=math.vec3();math.vec3();var tempMat4a$g=math.mat4();/** +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; ");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags = flags;");}src.push(" gl_Position = shadowProjMatrix * viewPosition;");src.push("}");src.push("gl_PointSize = pointSize;");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Instancing geometry depth drawing fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i301=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i301 1.0) {");src.push(" discard;");src.push(" }");if(clipping){src.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i302=0,_len68=sectionPlanesState.getNumAllocatedSectionPlanes();_i302<_len68;_i302++){src.push("if (sectionPlaneActive"+_i302+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i302+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i302+".xyz), 0.0, 1000.0);");src.push("}");}src.push("if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}}]);return VBOInstancingPointsShadowRenderer;}(VBOInstancingPointsRenderer);var tempVec3a$p=math.vec3();var tempVec3b$l=math.vec3();var tempVec3c$g=math.vec3();math.vec3();var tempMat4a$g=math.mat4();/** * @private */var VBOInstancingPointsSnapInitRenderer=/*#__PURE__*/function(_VBORenderer17){_inherits(VBOInstancingPointsSnapInitRenderer,_VBORenderer17);var _super111=_createSuper(VBOInstancingPointsSnapInitRenderer);function VBOInstancingPointsSnapInitRenderer(scene){_classCallCheck(this,VBOInstancingPointsSnapInitRenderer);return _super111.call(this,scene,false,{instancing:true});}_createClass(VBOInstancingPointsSnapInitRenderer,[{key:"drawLayer",value:function drawLayer(frameCtx,instancingLayer,renderPass){if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=instancingLayer.model;var scene=model.scene;var gl=scene.canvas.gl;var camera=scene.camera;var state=instancingLayer._state;var origin=instancingLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=instancingLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(this._vaoCache.has(instancingLayer)){gl.bindVertexArray(this._vaoCache.get(instancingLayer));}else{this._vaoCache.set(instancingLayer,this._makeVAO(state));}var coordinateScaler=tempVec3a$p;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);var rtcViewMatrix;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3b$l;if(origin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$g);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$g);frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);var offset=0;var mat4Size=4*4;this._matricesUniformBlockBufferData.set(rotationMatrixConjugate,0);this._matricesUniformBlockBufferData.set(rtcViewMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(camera.projMatrix,offset+=mat4Size);this._matricesUniformBlockBufferData.set(state.positionsDecodeMatrix,offset+=mat4Size);gl.bindBuffer(gl.UNIFORM_BUFFER,this._matricesUniformBlockBuffer);gl.bufferData(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,gl.DYNAMIC_DRAW);gl.bindBufferBase(gl.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}this.setSectionPlanesStateUniforms(instancingLayer);this._aModelMatrixCol0.bindArrayBuffer(state.modelMatrixCol0Buf);this._aModelMatrixCol1.bindArrayBuffer(state.modelMatrixCol1Buf);this._aModelMatrixCol2.bindArrayBuffer(state.modelMatrixCol2Buf);gl.vertexAttribDivisor(this._aModelMatrixCol0.location,1);gl.vertexAttribDivisor(this._aModelMatrixCol1.location,1);gl.vertexAttribDivisor(this._aModelMatrixCol2.location,1);if(this._aFlags){this._aFlags.bindArrayBuffer(state.flagsBuf);gl.vertexAttribDivisor(this._aFlags.location,1);}gl.drawArraysInstanced(gl.POINTS,0,state.positionsBuf.numItems,state.numInstances);// Cleanup @@ -15528,7 +15531,7 @@ gl.vertexAttribDivisor(this._aModelMatrixCol0.location,0);gl.vertexAttribDivisor src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.push("uniform bool pickInvisible;");this._addMatricesUniformBlockLines(src);src.push("uniform vec2 snapVectorA;");src.push("uniform vec2 snapInvVectorAB;");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;");src.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("out float vFlags;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// pickFlag = NOT_RENDERED | PICK // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex -src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i301=0;_i301> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i302=0;_i302 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");// src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"); +src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vWorldPosition = worldPosition;");if(clipping){src.push(" vFlags = flags;");}src.push("vPickColor = pickColor;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Points instancing pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("in float vFlags;");for(var _i303=0;_i303> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i304=0;_i304 0.0) { discard; }");src.push("}");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);");// src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"); // src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"); // src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"); src.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);");src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingPointsSnapInitRenderer;}(VBORenderer);var tempVec3a$o=math.vec3();var tempVec3b$k=math.vec3();var tempVec3c$f=math.vec3();math.vec3();var tempMat4a$f=math.mat4();/** @@ -15541,7 +15544,7 @@ src.push("in vec4 modelMatrixCol1;");src.push("in vec4 modelMatrixCol2;");src.pu // renderPass = PICK src.push("int pickFlag = int(flags) >> 12 & 0xF;");src.push("if (pickFlag != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");// Cull vertex src.push("} else {");src.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); ");src.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags = flags;");}src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i303=0;_i303> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i304=0;_i304 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingPointsSnapRenderer;}(VBORenderer);/** +src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// SnapInstancingDepthRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int layerNumber;");src.push("uniform vec3 coordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("in float vFlags;");for(var _i305=0;_i305> 16 & 0xF) == 1;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i306=0;_i306 0.0) { discard; }");src.push("}");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return VBOInstancingPointsSnapRenderer;}(VBORenderer);/** * @private */var VBOInstancingPointsRenderers=/*#__PURE__*/function(){function VBOInstancingPointsRenderers(scene){_classCallCheck(this,VBOInstancingPointsRenderers);this._scene=scene;}_createClass(VBOInstancingPointsRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._depthRenderer&&!this._depthRenderer.getValid()){this._depthRenderer.destroy();this._depthRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()){this._pickMeshRenderer.destroy();this._pickMeshRenderer=null;}if(this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()){this._pickDepthRenderer.destroy();this._pickDepthRenderer=null;}if(this._occlusionRenderer&&this._occlusionRenderer.getValid()===false){this._occlusionRenderer.destroy();this._occlusionRenderer=null;}if(this._shadowRenderer&&!this._shadowRenderer.getValid()){this._shadowRenderer.destroy();this._shadowRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}}},{key:"colorRenderer",get:function get(){if(!this._colorRenderer){this._colorRenderer=new VBOInstancingPointsColorRenderer(this._scene,false);}return this._colorRenderer;}},{key:"silhouetteRenderer",get:function get(){if(!this._silhouetteRenderer){this._silhouetteRenderer=new VBOInstancingPointsSilhouetteRenderer(this._scene);}return this._silhouetteRenderer;}},{key:"depthRenderer",get:function get(){if(!this._depthRenderer){this._depthRenderer=new VBOInstancingPointsDepthRenderer(this._scene);}return this._depthRenderer;}},{key:"pickMeshRenderer",get:function get(){if(!this._pickMeshRenderer){this._pickMeshRenderer=new VBOInstancingPointsPickMeshRenderer(this._scene);}return this._pickMeshRenderer;}},{key:"pickDepthRenderer",get:function get(){if(!this._pickDepthRenderer){this._pickDepthRenderer=new VBOInstancingPointsPickDepthRenderer(this._scene);}return this._pickDepthRenderer;}},{key:"occlusionRenderer",get:function get(){if(!this._occlusionRenderer){this._occlusionRenderer=new VBOInstancingPointsOcclusionRenderer(this._scene);}return this._occlusionRenderer;}},{key:"shadowRenderer",get:function get(){if(!this._shadowRenderer){this._shadowRenderer=new VBOInstancingPointsShadowRenderer(this._scene);}return this._shadowRenderer;}},{key:"snapInitRenderer",get:function get(){if(!this._snapInitRenderer){this._snapInitRenderer=new VBOInstancingPointsSnapInitRenderer(this._scene,false);}return this._snapInitRenderer;}},{key:"snapRenderer",get:function get(){if(!this._snapRenderer){this._snapRenderer=new VBOInstancingPointsSnapRenderer(this._scene);}return this._snapRenderer;}},{key:"_destroy",value:function _destroy(){if(this._colorRenderer){this._colorRenderer.destroy();}if(this._depthRenderer){this._depthRenderer.destroy();}if(this._silhouetteRenderer){this._silhouetteRenderer.destroy();}if(this._pickMeshRenderer){this._pickMeshRenderer.destroy();}if(this._pickDepthRenderer){this._pickDepthRenderer.destroy();}if(this._occlusionRenderer){this._occlusionRenderer.destroy();}if(this._shadowRenderer){this._shadowRenderer.destroy();}if(this._snapInitRenderer){this._snapInitRenderer.destroy();}if(this._snapRenderer){this._snapRenderer.destroy();}}}]);return VBOInstancingPointsRenderers;}();var cachedRenderers$1={};/** * @private @@ -15570,7 +15573,7 @@ src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:func colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null});// These counts are used to avoid unnecessary render passes 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;/** @private */this.numIndices=cfg.geometry.numIndices;// Per-instance arrays this._pickColors=[];this._offsets=[];// Modeling matrix per instance, array for each column -this._modelMatrixCol0=[];this._modelMatrixCol1=[];this._modelMatrixCol2=[];this._portions=[];this._meshes=[];this._aabb=math.collapseAABB3();this.aabbDirty=true;this._finalized=false;}_createClass(VBOInstancingPointsLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i305=0,len=this._meshes.length;_i3050){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8// 8 bits indices );gl.drawArrays(gl.LINES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16// 16 bits indices );gl.drawArrays(gl.LINES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32// 32 bits indices -);gl.drawArrays(gl.LINES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;console.error(this.errors);return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i306=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3060;var src=[];src.push("#version 300 es");src.push("// LinesDataTextureColorRenderer");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled);src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uPerObjectDecodeMatrix;");src.push("uniform highp sampler2D uPerObjectMatrix;");src.push("uniform lowp usampler2D uPerObjectColorAndFlags;");src.push("uniform mediump usampler2D uPerVertexPosition;");src.push("uniform highp usampler2D uPerLineIndices;");src.push("uniform mediump usampler2D uPerLineObject;");// src.push("uniform vec4 color;"); +);gl.drawArrays(gl.LINES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;console.error(this.errors);return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i308=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3080;var src=[];src.push("#version 300 es");src.push("// LinesDataTextureColorRenderer");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled);src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uPerObjectDecodeMatrix;");src.push("uniform highp sampler2D uPerObjectMatrix;");src.push("uniform lowp usampler2D uPerObjectColorAndFlags;");src.push("uniform mediump usampler2D uPerVertexPosition;");src.push("uniform highp usampler2D uPerLineIndices;");src.push("uniform mediump usampler2D uPerLineObject;");// src.push("uniform vec4 color;"); if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vColor;");src.push("void main(void) {");src.push(" int lineIndex = gl_VertexID / 2;");src.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;");src.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;");src.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");src.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.x = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE src.push(" if (int(flags.x) != renderPass) {");src.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);");// Cull vertex src.push(" return;");// Cull vertex src.push(" } else {");src.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));");src.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));");src.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;");src.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;");src.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;");src.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));");src.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;");src.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;");src.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;");src.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");src.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));");src.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);");src.push(" if (color.a == 0u) {");src.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);");// Cull vertex -src.push(" return;");src.push(" };");src.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push(" vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push(" vFragDepth = 1.0 + clipPos.w;");src.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push(" gl_Position = clipPos;");src.push(" vec4 rgb = vec4(color.rgba);");src.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// LinesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i307=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i307 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i308=0,_len69=sectionPlanesState.getNumAllocatedSectionPlanes();_i308<_len69;_i308++){src.push("if (sectionPlaneActive"+_i308+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i308+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i308+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXLinesColorRenderer;}();/** +src.push(" return;");src.push(" };");src.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push(" vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push(" vFragDepth = 1.0 + clipPos.w;");src.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push(" gl_Position = clipPos;");src.push(" vec4 rgb = vec4(color.rgba);");src.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// LinesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i309=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i309 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i310=0,_len69=sectionPlanesState.getNumAllocatedSectionPlanes();_i310<_len69;_i310++){src.push("if (sectionPlaneActive"+_i310+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i310+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i310+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXLinesColorRenderer;}();/** * @private */var DTXLinesRenderers=/*#__PURE__*/function(){function DTXLinesRenderers(scene){_classCallCheck(this,DTXLinesRenderers);this._scene=scene;}_createClass(DTXLinesRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}}},{key:"eagerCreateRenders",value:function eagerCreateRenders(){// Pre-initialize certain renderers that would otherwise be lazy-initialised // on user interaction, such as picking or emphasis, so that there is no delay @@ -15701,13 +15704,13 @@ this.numPortions=numPortions;var textureWidth=512*8;var textureHeight=Math.ceil( // - col5: (packed Uint32 bytes as RGBA) index base offset // // - col6: (packed Uint32 bytes as RGBA) edge index base offset // // - col7: (packed 4 bytes as RGBA) is-solid flag for objects -var texArray=new Uint8Array(4*textureWidth*textureHeight);dataTextureRamStats$1.sizeDataColorsAndFlags+=texArray.byteLength;dataTextureRamStats$1.numberOfTextures++;for(var _i309=0;_i309>24&255,vertexBases[_i309]>>16&255,vertexBases[_i309]>>8&255,vertexBases[_i309]&255],_i309*32+16);// lines index base offset -texArray.set([indexBaseOffsets[_i309]>>24&255,indexBaseOffsets[_i309]>>16&255,indexBaseOffsets[_i309]>>8&255,indexBaseOffsets[_i309]&255],_i309*32+20);// // edge index base offset +texArray.set([vertexBases[_i311]>>24&255,vertexBases[_i311]>>16&255,vertexBases[_i311]>>8&255,vertexBases[_i311]&255],_i311*32+16);// lines index base offset +texArray.set([indexBaseOffsets[_i311]>>24&255,indexBaseOffsets[_i311]>>16&255,indexBaseOffsets[_i311]>>8&255,indexBaseOffsets[_i311]&255],_i311*32+20);// // edge index base offset // texArray.set( // [ // (edgeIndexBaseOffsets[i] >> 24) & 255, @@ -15741,8 +15744,8 @@ texArray.set([indexBaseOffsets[_i309]>>24&255,indexBaseOffsets[_i309]>>16&255,in * @returns {BindableDataTexture} */},{key:"generateTextureForInstancingMatrices",value:function generateTextureForInstancingMatrices(gl,instanceMatrices){var numMatrices=instanceMatrices.length;if(numMatrices===0){throw"num instance matrices===0";}// in one row we can fit 512 matrices var textureWidth=512*4;var textureHeight=Math.ceil(numMatrices/(textureWidth/4));var texArray=new Float32Array(4*textureWidth*textureHeight);// dataTextureRamStats.sizeDataPositionDecodeMatrices += texArray.byteLength; -dataTextureRamStats$1.numberOfTextures++;for(var _i310=0;_i310} positionsArrays Arrays of quantized positions in the layer * @param lenPositions @@ -15786,7 +15789,7 @@ texArray.set(positionDecodeMatrices[_i311],_i311*16);}var texture=gl.createTextu * - a number of rows R where R*1024 is just >= than the number of vertices (positions / 3) * * @returns {BindableDataTexture} - */},{key:"generateTextureForPositions",value:function generateTextureForPositions(gl,positionsArrays,lenPositions){var numVertices=lenPositions/3;var textureWidth=4096;var textureHeight=Math.ceil(numVertices/textureWidth);if(textureHeight===0){throw"texture height===0";}var texArraySize=textureWidth*textureHeight*3;var texArray=new Uint16Array(texArraySize);dataTextureRamStats$1.sizeDataTexturePositions+=texArray.byteLength;dataTextureRamStats$1.numberOfTextures++;for(var _i315=0,j=0,len=positionsArrays.length;_i315} portionIdsArray * @@ -15796,12 +15799,12 @@ texArray.set(positionDecodeMatrices[_i311],_i311*16);}var texture=gl.createTextu */var DTXLinesLayer=/*#__PURE__*/function(){function DTXLinesLayer(model,cfg){_classCallCheck(this,DTXLinesLayer);console.info("Creating DTXLinesLayer");dataTextureRamStats$1.numberOfLayers++;this._layerNumber=numLayers$1++;this.sortId="TriDTX-".concat(this._layerNumber);// State sorting key. this.layerIndex=cfg.layerIndex;// Index of this DTXLinesLayer in {@link SceneModel#_layerList}. this._renderers=getRenderers$1(model.scene);this.model=model;this._buffer=new DTXLinesBuffer();this._dataTextureState=new DTXLinesState();this._dataTextureGenerator=new DTXLinesTextureFactory();this._state=new RenderState({origin:math.vec3(cfg.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0});this._numPortions=0;// These counts are used to avoid unnecessary render passes -this._numVisibleLayerPortions=0;this._numTransparentLayerPortions=0;this._numXRayedLayerPortions=0;this._numSelectedLayerPortions=0;this._numHighlightedLayerPortions=0;this._numClippableLayerPortions=0;this._numPickableLayerPortions=0;this._numCulledLayerPortions=0;this._subPortions=[];this._portionToSubPortionsMap=[];this._bucketGeometries={};this._meshes=[];this._aabb=math.collapseAABB3();this.aabbDirty=true;this._numUpdatesInFrame=0;this._finalized=false;}_createClass(DTXLinesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i316=0,len=this._meshes.length;_i316MAX_NUMBER_OF_OBJECTS_IN_LAYER$1){dataTextureRamStats$1.cannotCreatePortion.because10BitsObjectId++;}var retVal=this._numPortions+numNewPortions<=MAX_NUMBER_OF_OBJECTS_IN_LAYER$1;var bucketIndex=0;// TODO: Is this a bug? +this._numVisibleLayerPortions=0;this._numTransparentLayerPortions=0;this._numXRayedLayerPortions=0;this._numSelectedLayerPortions=0;this._numHighlightedLayerPortions=0;this._numClippableLayerPortions=0;this._numPickableLayerPortions=0;this._numCulledLayerPortions=0;this._subPortions=[];this._portionToSubPortionsMap=[];this._bucketGeometries={};this._meshes=[];this._aabb=math.collapseAABB3();this.aabbDirty=true;this._numUpdatesInFrame=0;this._finalized=false;}_createClass(DTXLinesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i318=0,len=this._meshes.length;_i318MAX_NUMBER_OF_OBJECTS_IN_LAYER$1){dataTextureRamStats$1.cannotCreatePortion.because10BitsObjectId++;}var retVal=this._numPortions+numNewPortions<=MAX_NUMBER_OF_OBJECTS_IN_LAYER$1;var bucketIndex=0;// TODO: Is this a bug? var bucketGeometryId=portionCfg.geometryId!==undefined&&portionCfg.geometryId!==null?"".concat(portionCfg.geometryId,"#").concat(bucketIndex):"".concat(portionCfg.id,"#").concat(bucketIndex);var alreadyHasPortionGeometry=this._bucketGeometries[bucketGeometryId];if(!alreadyHasPortionGeometry){var maxIndicesOfAnyBits=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);var numVertices=0;var _numIndices=0;portionCfg.buckets.forEach(function(bucket){numVertices+=bucket.positionsCompressed.length/3;_numIndices+=bucket.indices.length/2;});if(this._state.numVertices+numVertices>MAX_DATA_TEXTURE_HEIGHT$1*4096||maxIndicesOfAnyBits+_numIndices>MAX_DATA_TEXTURE_HEIGHT$1*4096){dataTextureRamStats$1.cannotCreatePortion.becauseTextureSize++;}retVal&&(retVal=this._state.numVertices+numVertices<=MAX_DATA_TEXTURE_HEIGHT$1*4096&&maxIndicesOfAnyBits+_numIndices<=MAX_DATA_TEXTURE_HEIGHT$1*4096);}return retVal;}},{key:"createPortion",value:function createPortion(mesh,portionCfg){var _this70=this;if(this._finalized){throw"Already finalized";}var subPortionIds=[];// const portionAABB = portionCfg.worldAABB; portionCfg.buckets.forEach(function(bucket,bucketIndex){var bucketGeometryId=portionCfg.geometryId!==undefined&&portionCfg.geometryId!==null?"".concat(portionCfg.geometryId,"#").concat(bucketIndex):"".concat(portionCfg.id,"#").concat(bucketIndex);var bucketGeometry=_this70._bucketGeometries[bucketGeometryId];if(!bucketGeometry){bucketGeometry=_this70._createBucketGeometry(portionCfg,bucket);_this70._bucketGeometries[bucketGeometryId]=bucketGeometry;}// const subPortionAABB = math.collapseAABB3(tempAABB3b); var subPortionId=_this70._createSubPortion(portionCfg,bucketGeometry,bucket);//math.expandAABB3(portionAABB, subPortionAABB); subPortionIds.push(subPortionId);});var portionId=this._portionToSubPortionsMap.length;this._portionToSubPortionsMap.push(subPortionIds);this.model.numPortions++;this._meshes.push(mesh);return portionId;}},{key:"_createBucketGeometry",value:function _createBucketGeometry(portionCfg,bucket){if(bucket.indices){var alignedIndicesLen=Math.ceil(bucket.indices.length/2/INDICES_EDGE_INDICES_ALIGNEMENT_SIZE$1)*INDICES_EDGE_INDICES_ALIGNEMENT_SIZE$1*2;dataTextureRamStats$1.overheadSizeAlignementIndices+=2*(alignedIndicesLen-bucket.indices.length);var alignedIndices=new Uint32Array(alignedIndicesLen);alignedIndices.fill(0);alignedIndices.set(bucket.indices);bucket.indices=alignedIndices;}var positionsCompressed=bucket.positionsCompressed;var indices=bucket.indices;var buffer=this._buffer;buffer.positionsCompressed.push(positionsCompressed);var vertexBase=buffer.lenPositionsCompressed/3;var numVertices=positionsCompressed.length/3;buffer.lenPositionsCompressed+=positionsCompressed.length;var indicesBase;var numLines=0;if(indices){numLines=indices.length/2;var indicesBuffer;if(numVertices<=1<<8){indicesBuffer=buffer.indices8Bits;indicesBase=buffer.lenIndices8Bits/2;buffer.lenIndices8Bits+=indices.length;}else if(numVertices<=1<<16){indicesBuffer=buffer.indices16Bits;indicesBase=buffer.lenIndices16Bits/2;buffer.lenIndices16Bits+=indices.length;}else{indicesBuffer=buffer.indices32Bits;indicesBase=buffer.lenIndices32Bits/2;buffer.lenIndices32Bits+=indices.length;}indicesBuffer.push(indices);}this._state.numVertices+=numVertices;dataTextureRamStats$1.numberOfGeometries++;var bucketGeometry={vertexBase:vertexBase,numVertices:numVertices,numLines:numLines,indicesBase:indicesBase};return bucketGeometry;}},{key:"_createSubPortion",value:function _createSubPortion(portionCfg,bucketGeometry){var color=portionCfg.color;var colors=portionCfg.colors;var opacity=portionCfg.opacity;var meshMatrix=portionCfg.meshMatrix;var pickColor=portionCfg.pickColor;var buffer=this._buffer;var state=this._state;buffer.perObjectPositionsDecodeMatrices.push(portionCfg.positionsDecodeMatrix);buffer.perObjectInstancePositioningMatrices.push(meshMatrix||DEFAULT_MATRIX$2);buffer.perObjectSolid.push(!!portionCfg.solid);if(colors){buffer.perObjectColors.push([colors[0]*255,colors[1]*255,colors[2]*255,255]);}else if(color){// Color is pre-quantized by SceneModel -buffer.perObjectColors.push([color[0],color[1],color[2],opacity]);}buffer.perObjectPickColors.push(pickColor);buffer.perObjectVertexBases.push(bucketGeometry.vertexBase);{var currentNumIndices;if(bucketGeometry.numVertices<=1<<8){currentNumIndices=state.numIndices8Bits;}else if(bucketGeometry.numVertices<=1<<16){currentNumIndices=state.numIndices16Bits;}else{currentNumIndices=state.numIndices32Bits;}buffer.perObjectIndexBaseOffsets.push(currentNumIndices/2-bucketGeometry.indicesBase);}var subPortionId=this._subPortions.length;if(bucketGeometry.numLines>0){var _numIndices2=bucketGeometry.numLines*2;var indicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){indicesPortionIdBuffer=buffer.perLineNumberPortionId8Bits;state.numIndices8Bits+=_numIndices2;dataTextureRamStats$1.totalLines8Bits+=bucketGeometry.numLines;}else if(bucketGeometry.numVertices<=1<<16){indicesPortionIdBuffer=buffer.perLineNumberPortionId16Bits;state.numIndices16Bits+=_numIndices2;dataTextureRamStats$1.totalLines16Bits+=bucketGeometry.numLines;}else{indicesPortionIdBuffer=buffer.perLineNumberPortionId32Bits;state.numIndices32Bits+=_numIndices2;dataTextureRamStats$1.totalLines32Bits+=bucketGeometry.numLines;}dataTextureRamStats$1.totalLines+=bucketGeometry.numLines;for(var _i317=0;_i3170){var _numIndices2=bucketGeometry.numLines*2;var indicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){indicesPortionIdBuffer=buffer.perLineNumberPortionId8Bits;state.numIndices8Bits+=_numIndices2;dataTextureRamStats$1.totalLines8Bits+=bucketGeometry.numLines;}else if(bucketGeometry.numVertices<=1<<16){indicesPortionIdBuffer=buffer.perLineNumberPortionId16Bits;state.numIndices16Bits+=_numIndices2;dataTextureRamStats$1.totalLines16Bits+=bucketGeometry.numLines;}else{indicesPortionIdBuffer=buffer.perLineNumberPortionId32Bits;state.numIndices32Bits+=_numIndices2;dataTextureRamStats$1.totalLines32Bits+=bucketGeometry.numLines;}dataTextureRamStats$1.totalLines+=bucketGeometry.numLines;for(var _i319=0;_i319=MAX_OBJECT_UPDATES_IN_FRAME_WITHOUT_BATCHED_UPDATE$1){this._beginDeferredFlags();// Subsequent flags updates now deferred }gl.bindTexture(gl.TEXTURE_2D,textureState.texturePerObjectColorsAndFlags._texture);gl.texSubImage2D(gl.TEXTURE_2D,0,// level @@ -15841,7 +15844,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4$1);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"setTransparent",value:function setTransparent(portionId,flags,transparent){if(transparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}else{this._numTransparentLayerPortions--;this.model.numTransparentLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"_setFlags",value:function _setFlags(portionId,flags,transparent){var deferred=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i319=0,len=subPortionIds.length;_i3193&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);// Color +}},{key:"setTransparent",value:function setTransparent(portionId,flags,transparent){if(transparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}else{this._numTransparentLayerPortions--;this.model.numTransparentLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"_setFlags",value:function _setFlags(portionId,flags,transparent){var deferred=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i321=0,len=subPortionIds.length;_i3213&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);// Color var f0;if(!visible||culled||xrayed){// Highlight & select are layered on top of color - not mutually exclusive f0=RENDER_PASSES.NOT_RENDERED;}else{if(transparent){f0=RENDER_PASSES.COLOR_TRANSPARENT;}else{f0=RENDER_PASSES.COLOR_OPAQUE;}}// Silhouette var f1;if(!visible||culled){f1=RENDER_PASSES.NOT_RENDERED;}else if(selected){f1=RENDER_PASSES.SILHOUETTE_SELECTED;}else if(highlighted){f1=RENDER_PASSES.SILHOUETTE_HIGHLIGHTED;}else if(xrayed){f1=RENDER_PASSES.SILHOUETTE_XRAYED;}else{f1=RENDER_PASSES.NOT_RENDERED;}// // Edges @@ -15874,7 +15877,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4$1);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"_setDeferredFlags",value:function _setDeferredFlags(){}},{key:"_setFlags2",value:function _setFlags2(portionId,flags){var deferred=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i320=0,len=subPortionIds.length;_i3202&&arguments[2]!==undefined?arguments[2]:false;if(!this._finalized){throw"Not finalized";}var clippable=!!(flags&ENTITY_FLAGS.CLIPPABLE)?255:0;var textureState=this._dataTextureState;var gl=this.model.scene.canvas.gl;tempUint8Array4$1[0]=clippable;tempUint8Array4$1[1]=0;tempUint8Array4$1[2]=1;tempUint8Array4$1[3]=2;// object flags2 +}},{key:"_setDeferredFlags",value:function _setDeferredFlags(){}},{key:"_setFlags2",value:function _setFlags2(portionId,flags){var deferred=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i322=0,len=subPortionIds.length;_i3222&&arguments[2]!==undefined?arguments[2]:false;if(!this._finalized){throw"Not finalized";}var clippable=!!(flags&ENTITY_FLAGS.CLIPPABLE)?255:0;var textureState=this._dataTextureState;var gl=this.model.scene.canvas.gl;tempUint8Array4$1[0]=clippable;tempUint8Array4$1[1]=0;tempUint8Array4$1[2]=1;tempUint8Array4$1[3]=2;// object flags2 textureState.texturePerObjectColorsAndFlags._textureData.set(tempUint8Array4$1,subPortionId*32+12);if(this._deferredSetFlagsActive||deferred){// console.log("_subPortionSetFlags2 set flags defer"); this._deferredSetFlagsDirty=true;return;}if(++this._numUpdatesInFrame>=MAX_OBJECT_UPDATES_IN_FRAME_WITHOUT_BATCHED_UPDATE$1){this._beginDeferredFlags();// Subsequent flags updates now deferred }gl.bindTexture(gl.TEXTURE_2D,textureState.texturePerObjectColorsAndFlags._texture);gl.texSubImage2D(gl.TEXTURE_2D,0,// level @@ -15883,7 +15886,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4$1);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"_setDeferredFlags2",value:function _setDeferredFlags2(){}},{key:"setOffset",value:function setOffset(portionId,offset){var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i321=0,len=subPortionIds.length;_i3210){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;var lightsState=scene._lightsState;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;console.error(this.errors);return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uLightAmbient=program.getLocation("lightAmbient");this._uLightColor=[];this._uLightDir=[];this._uLightPos=[];this._uLightAttenuation=[];var lights=lightsState.lights;var light;for(var _i323=0,len=lights.length;_i3230;var light;var src=[];src.push("#version 300 es");src.push("// TrianglesDataTextureColorRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("uniform vec4 lightAmbient;");for(var _i326=0,len=lightsState.lights.length;_i3260;var light;var src=[];src.push("#version 300 es");src.push("// TrianglesDataTextureColorRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("uniform vec4 lightAmbient;");for(var _i328=0,len=lightsState.lights.length;_i328> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.x = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT @@ -15942,7 +15945,7 @@ src.push("} else {");src.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjec src.push(" return;");src.push("};");src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");// when the geometry is not solid, if needed, flip the triangle winding src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");// src.push("vColor = vec4(vec3(1, -1, 0)*dot(normalize(position.xyz - uCameraEyeRtcInQuantizedSpace), normal), 1);") src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");// src.push("vColor = vec4(vec3(1, -1, 0)*viewNormal.z, 1);") -src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(var _i327=0,_len71=lightsState.lights.length;_i327<_len71;_i327++){light=lightsState.lights[_i327];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i327+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i327+", 0.0)).xyz);");}}else if(light.type==="point"){if(light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i327+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i327+", 0.0)).xyz);");}}else if(light.type==="spot"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i327+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i327+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i327+".rgb * lightColor"+_i327+".a);");}src.push("vec3 rgb = vec3(color.rgb) / 255.0;");src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i328=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i328 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i329=0,_len72=sectionPlanesState.getNumAllocatedSectionPlanes();_i329<_len72;_i329++){src.push("if (sectionPlaneActive"+_i329+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i329+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i329+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");//src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"); +src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);");src.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);");src.push("float lambertian = 1.0;");for(var _i329=0,_len71=lightsState.lights.length;_i329<_len71;_i329++){light=lightsState.lights[_i329];if(light.type==="ambient"){continue;}if(light.type==="dir"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i329+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i329+", 0.0)).xyz);");}}else if(light.type==="point"){if(light.space==="view"){src.push("viewLightDir = -normalize(lightPos"+_i329+" - viewPosition.xyz);");}else{src.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+_i329+", 0.0)).xyz);");}}else if(light.type==="spot"){if(light.space==="view"){src.push("viewLightDir = normalize(lightDir"+_i329+");");}else{src.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+_i329+", 0.0)).xyz);");}}else{continue;}src.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);");src.push("reflectedColor += lambertian * (lightColor"+_i329+".rgb * lightColor"+_i329+".a);");}src.push("vec3 rgb = vec3(color.rgb) / 255.0;");src.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(this._withSAO){src.push("uniform sampler2D uOcclusionTexture;");src.push("uniform vec4 uSAOParams;");src.push("const float packUpscale = 256. / 255.;");src.push("const float unpackDownScale = 255. / 256.;");src.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );");src.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );");src.push("float unpackRGBToFloat( const in vec4 v ) {");src.push(" return dot( v, unPackFactors );");src.push("}");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i330=0,len=sectionPlanesState.getNumAllocatedSectionPlanes();_i330 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i331=0,_len72=sectionPlanesState.getNumAllocatedSectionPlanes();_i331<_len72;_i331++){src.push("if (sectionPlaneActive"+_i331+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i331+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i331+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");//src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"); }if(this._withSAO){// Doing SAO blend in the main solid fill draw shader just so that edge lines can be drawn over the top // Would be more efficient to defer this, then render lines later, using same depth buffer for Z-reject src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewportHeight = uSAOParams[1];");src.push(" float blendCutoff = uSAOParams[2];");src.push(" float blendFactor = uSAOParams[3];");src.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);");src.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;");src.push(" outColor = vec4(vColor.rgb * ambient, 1.0);");}else{src.push(" outColor = vColor;");}src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesColorRenderer;}();var defaultColor$1=new Float32Array([1,1,1]);var tempVec3a$l=math.vec3();var tempVec3b$h=math.vec3();var tempVec3c$d=math.vec3();math.vec3();var tempMat4a$b=math.mat4();/** @@ -15950,7 +15953,7 @@ src.push(" float viewportWidth = uSAOParams[0];");src.push(" float viewp */var DTXTrianglesSilhouetteRenderer=/*#__PURE__*/function(){function DTXTrianglesSilhouetteRenderer(scene,primitiveType){_classCallCheck(this,DTXTrianglesSilhouetteRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesSilhouetteRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var scene=this._scene;var camera=scene.camera;var model=dataTextureLayer.model;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var viewMatrix=camera.viewMatrix;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx,state);}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3a$l;if(origin){var rotatedOrigin=tempVec3b$h;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$b);rtcCameraEye=tempVec3c$d;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform1i(this._uRenderPass,renderPass);gl.uniformMatrix4fv(this._uWorldMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);if(renderPass===RENDER_PASSES.SILHOUETTE_XRAYED){var material=scene.xrayMaterial._state;var fillColor=material.fillColor;var fillAlpha=material.fillAlpha;gl.uniform4f(this._uColor,fillColor[0],fillColor[1],fillColor[2],fillAlpha);}else if(renderPass===RENDER_PASSES.SILHOUETTE_HIGHLIGHTED){var _material3=scene.highlightMaterial._state;var _fillColor=_material3.fillColor;var _fillAlpha=_material3.fillAlpha;gl.uniform4f(this._uColor,_fillColor[0],_fillColor[1],_fillColor[2],_fillAlpha);}else if(renderPass===RENDER_PASSES.SILHOUETTE_SELECTED){var _material4=scene.selectedMaterial._state;var _fillColor2=_material4.fillColor;var _fillAlpha2=_material4.fillAlpha;gl.uniform4f(this._uColor,_fillColor2[0],_fillColor2[1],_fillColor2[2],_fillAlpha2);}else{gl.uniform4fv(this._uColor,defaultColor$1);}if(scene.logarithmicDepthBufferEnabled){var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uColor=program.getLocation("color");this._uWorldMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i330=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3300;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture silhouette vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");// src.push("uniform sampler2D uOcclusionTexture;"); +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uColor=program.getLocation("color");this._uWorldMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i332=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3320;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture silhouette vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");// src.push("uniform sampler2D uOcclusionTexture;"); src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 @@ -15962,12 +15965,12 @@ src.push("} else {");// get vertex base src.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));");src.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));");src.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;");src.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;");src.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;");src.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));");src.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;");src.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;");src.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;");src.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;");// get position src.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));");src.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));");src.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));");// get normal src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");// when the geometry is not solid, if needed, flip the triangle winding -src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i331=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i331 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i332=0,_len73=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i332<_len73;_i332++){src.push("if (sectionPlaneActive"+_i332+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i332+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i332+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = color;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSilhouetteRenderer;}();var defaultColor=new Float32Array([0,0,0,1]);var tempVec3a$k=math.vec3();var tempVec3b$g=math.vec3();math.vec3();var tempMat4a$a=math.mat4();/** +src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i333=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i333 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i334=0,_len73=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i334<_len73;_i334++){src.push("if (sectionPlaneActive"+_i334+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i334+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i334+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = color;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSilhouetteRenderer;}();var defaultColor=new Float32Array([0,0,0,1]);var tempVec3a$k=math.vec3();var tempVec3b$g=math.vec3();math.vec3();var tempMat4a$a=math.mat4();/** * @private */var DTXTrianglesEdgesRenderer=/*#__PURE__*/function(){function DTXTrianglesEdgesRenderer(scene){_classCallCheck(this,DTXTrianglesEdgesRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesEdgesRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var viewMatrix=camera.viewMatrix;if(!this._program){this._allocate(dataTextureLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$k;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3b$g);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$a);}else{rtcViewMatrix=viewMatrix;}gl.uniform1i(this._uRenderPass,renderPass);gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);if(renderPass===RENDER_PASSES.EDGES_XRAYED){var material=scene.xrayMaterial._state;var edgeColor=material.edgeColor;var edgeAlpha=material.edgeAlpha;gl.uniform4f(this._uColor,edgeColor[0],edgeColor[1],edgeColor[2],edgeAlpha);}else if(renderPass===RENDER_PASSES.EDGES_HIGHLIGHTED){var _material5=scene.highlightMaterial._state;var _edgeColor=_material5.edgeColor;var _edgeAlpha=_material5.edgeAlpha;gl.uniform4f(this._uColor,_edgeColor[0],_edgeColor[1],_edgeColor[2],_edgeAlpha);}else if(renderPass===RENDER_PASSES.EDGES_SELECTED){var _material6=scene.selectedMaterial._state;var _edgeColor2=_material6.edgeColor;var _edgeAlpha2=_material6.edgeAlpha;gl.uniform4f(this._uColor,_edgeColor2[0],_edgeColor2[1],_edgeColor2[2],_edgeAlpha2);}else{gl.uniform4fv(this._uColor,defaultColor);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8// 8 bits edge indices );gl.drawArrays(gl.LINES,0,state.numEdgeIndices8Bits);}if(state.numEdgeIndices16Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16// 16 bits edge indices );gl.drawArrays(gl.LINES,0,state.numEdgeIndices16Bits);}if(state.numEdgeIndices32Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32// 32 bits edge indices -);gl.drawArrays(gl.LINES,0,state.numEdgeIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uColor=program.getLocation("color");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uWorldMatrix=program.getLocation("worldMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i333=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3330;var src=[];src.push("#version 300 es");src.push("// DTXTrianglesEdgesRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");// if (scene.entityOffsetsEnabled) { +);gl.drawArrays(gl.LINES,0,state.numEdgeIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uColor=program.getLocation("color");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uWorldMatrix=program.getLocation("worldMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i335=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3350;var src=[];src.push("#version 300 es");src.push("// DTXTrianglesEdgesRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");// if (scene.entityOffsetsEnabled) { // src.push("in vec3 offset;"); // } src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;");src.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;");src.push("uniform vec4 color;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vColor;");src.push("void main(void) {");// constants @@ -15980,12 +15983,12 @@ src.push(" return;");// Cull vertex src.push("} else {");// get vertex base src.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));");src.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));");src.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;");src.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;");src.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;");src.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));");src.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;");src.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;");src.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;");src.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// get position -src.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));");src.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// DTXTrianglesEdgesRenderer fragment shader");if(scene.logarithmicDepthBufferEnabled){src.push("#extension GL_EXT_frag_depth : enable");}src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i334=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i334 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i335=0,_len74=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i335<_len74;_i335++){src.push("if (sectionPlaneActive"+_i335+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i335+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i335+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesEdgesRenderer;}();var tempVec3a$j=math.vec3();var tempVec3b$f=math.vec3();var tempMat4a$9=math.mat4();/** +src.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));");src.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vColor = vec4(color.r, color.g, color.b, color.a);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// DTXTrianglesEdgesRenderer fragment shader");if(scene.logarithmicDepthBufferEnabled){src.push("#extension GL_EXT_frag_depth : enable");}src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i336=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i336 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i337=0,_len74=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i337<_len74;_i337++){src.push("if (sectionPlaneActive"+_i337+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i337+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i337+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesEdgesRenderer;}();var tempVec3a$j=math.vec3();var tempVec3b$f=math.vec3();var tempMat4a$9=math.mat4();/** * @private */var DTXTrianglesEdgesColorRenderer=/*#__PURE__*/function(){function DTXTrianglesEdgesColorRenderer(scene){_classCallCheck(this,DTXTrianglesEdgesColorRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesEdgesColorRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var viewMatrix=camera.viewMatrix;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$j;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3b$f);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$9);}else{rtcViewMatrix=viewMatrix;}gl.uniform1i(this._uRenderPass,renderPass);gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8// 8 bits edge indices );gl.drawArrays(gl.LINES,0,state.numEdgeIndices8Bits);}if(state.numEdgeIndices16Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16// 16 bits edge indices );gl.drawArrays(gl.LINES,0,state.numEdgeIndices16Bits);}if(state.numEdgeIndices32Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32// 32 bits edge indices -);gl.drawArrays(gl.LINES,0,state.numEdgeIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i336=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3360;var src=[];src.push("#version 300 es");src.push("// TrianglesDataTextureEdgesColorRenderer");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled);src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform highp sampler2D uObjectPerObjectOffsets;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;");src.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;");// src.push("uniform vec4 color;"); if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vColor;");src.push("void main(void) {");// constants src.push("int edgeIndex = gl_VertexID / 2;");// get packed object-id @@ -16000,13 +16003,13 @@ src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(object src.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));");// get color src.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);");src.push("if (color.a == 0u) {");src.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);");// Cull vertex src.push(" return;");src.push("};");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("vec4 rgb = vec4(color.rgba);");//src.push("vColor = vec4(float(color.r-100.0) / 255.0, float(color.g-100.0) / 255.0, float(color.b-100.0) / 255.0, float(color.a) / 255.0);"); -src.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureEdgesColorRenderer");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i337=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i337 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i338=0,_len75=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i338<_len75;_i338++){src.push("if (sectionPlaneActive"+_i338+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i338+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i338+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesEdgesColorRenderer;}();var tempVec3a$i=math.vec3();var tempVec3b$e=math.vec3();var tempVec3c$c=math.vec3();var tempMat4a$8=math.mat4();/** +src.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureEdgesColorRenderer");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i339=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i339 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i340=0,_len75=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i340<_len75;_i340++){src.push("if (sectionPlaneActive"+_i340+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i340+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i340+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { discard; }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" outColor = vColor;");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesEdgesColorRenderer;}();var tempVec3a$i=math.vec3();var tempVec3b$e=math.vec3();var tempVec3c$c=math.vec3();var tempMat4a$8=math.mat4();/** * @private */var DTXTrianglesPickMeshRenderer=/*#__PURE__*/function(){function DTXTrianglesPickMeshRenderer(scene){_classCallCheck(this,DTXTrianglesPickMeshRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesPickMeshRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){if(!this._program){this._allocate(dataTextureLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx);}var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$i;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3b$e);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(camera.viewMatrix,rtcOrigin,tempMat4a$8);rtcCameraEye=tempVec3c$c;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=camera.viewMatrix;rtcCameraEye=camera.eye;}gl.uniform2fv(this._uPickClipPos,frameCtx.pickClipPos);gl.uniform2f(this._uDrawingBufferSize,gl.drawingBufferWidth,gl.drawingBufferHeight);gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform1i(this._uRenderPass,renderPass);if(scene.logarithmicDepthBufferEnabled){var logDepthBufFC=2.0/(Math.log(camera.project.far+1.0)/Math.LN2);// TODO: Far from pick project matrix? gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i339=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3390;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform bool pickInvisible;");// src.push("uniform sampler2D uOcclusionTexture;"); +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i341=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3410;var src=[];src.push("#version 300 es");src.push("// Batched geometry picking vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform bool pickInvisible;");// src.push("uniform sampler2D uOcclusionTexture;"); src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("uniform vec2 drawingBufferSize;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("smooth out vec4 vWorldPosition;");src.push("flat out uvec4 vFlags2;");}src.push("out vec4 vPickColor;");src.push("void main(void) {");src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.w = NOT_RENDERED | PICK @@ -16026,7 +16029,7 @@ src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {" gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i340=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3400;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture pick depth vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform bool pickInvisible;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("uniform vec2 drawingBufferSize;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vViewPosition;");src.push("void main(void) {");// constants +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i342=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3420;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture pick depth vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform bool pickInvisible;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("uniform vec2 drawingBufferSize;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vViewPosition;");src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.w = NOT_RENDERED | PICK @@ -16046,18 +16049,18 @@ src.push("}");return src;}},{key:"webglContextRestored",value:function webglCont var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;var coordinateScaler=tempVec3a$g;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3b$c;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3c$a);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$6);rtcCameraEye=tempVec3d$2;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this.uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this.uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8// 8 bits edge indices );gl.drawArrays(glMode,0,state.numEdgeIndices8Bits);}if(state.numEdgeIndices16Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16// 16 bits edge indices );gl.drawArrays(glMode,0,state.numEdgeIndices16Bits);}if(state.numEdgeIndices32Bits>0){textureState.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32// 32 bits edge indices -);gl.drawArrays(glMode,0,state.numEdgeIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i341=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3410;var src=[];src.push("#version 300 es");src.push("// Batched geometry edges drawing vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;");src.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 uSnapVectorA;");src.push("uniform vec2 uSnapInvVectorAB;");src.push("vec3 positions[3];");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;");src.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vViewPosition;");src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// constants +);gl.drawArrays(glMode,0,state.numEdgeIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i343=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3430;var src=[];src.push("#version 300 es");src.push("// Batched geometry edges drawing vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;");src.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 uSnapVectorA;");src.push("uniform vec2 uSnapInvVectorAB;");src.push("vec3 positions[3];");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out float isPerspective;");}src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;");src.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("out vec4 vViewPosition;");src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// constants src.push("int edgeIndex = gl_VertexID / 2;");// get packed object-id src.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");src.push("{");// get vertex base src.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));");src.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));");src.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;");src.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;");src.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;");src.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));");src.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;");src.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;");src.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;");src.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));");src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");src.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("relativeToOriginPosition = worldPosition.xyz;");src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2.r;");}src.push("vViewPosition = viewPosition;");src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");src.push("vViewPosition = clipPos;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push("gl_PointSize = 1.0;");// Windows needs this? -src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int uLayerNumber;");src.push("uniform vec3 uCoordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i342=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i342 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSnapRenderer;}();var tempVec3a$f=math.vec3();var tempVec3b$b=math.vec3();var tempVec3c$9=math.vec3();var tempVec3d$1=math.vec3();math.vec3();var tempMat4a$5=math.mat4();/** +src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture pick depth fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int uLayerNumber;");src.push("uniform vec3 uCoordinateScaler;");if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i344=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i344 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSnapRenderer;}();var tempVec3a$f=math.vec3();var tempVec3b$b=math.vec3();var tempVec3c$9=math.vec3();var tempVec3d$1=math.vec3();math.vec3();var tempMat4a$5=math.mat4();/** * @private */var DTXTrianglesSnapInitRenderer=/*#__PURE__*/function(){function DTXTrianglesSnapInitRenderer(scene){_classCallCheck(this,DTXTrianglesSnapInitRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesSnapInitRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){if(!this._program){this._allocate();}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var aabb=dataTextureLayer.aabb;// Per-layer AABB for best RTC accuracy var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;var coordinateScaler=tempVec3a$f;coordinateScaler[0]=math.safeInv(aabb[3]-aabb[0])*math.MAX_INT;coordinateScaler[1]=math.safeInv(aabb[4]-aabb[1])*math.MAX_INT;coordinateScaler[2]=math.safeInv(aabb[5]-aabb[2])*math.MAX_INT;frameCtx.snapPickCoordinateScale[0]=math.safeInv(coordinateScaler[0]);frameCtx.snapPickCoordinateScale[1]=math.safeInv(coordinateScaler[1]);frameCtx.snapPickCoordinateScale[2]=math.safeInv(coordinateScaler[2]);textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3b$b;if(gotOrigin){var rotatedOrigin=tempVec3c$9;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$5);rtcCameraEye=tempVec3d$1;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];frameCtx.snapPickOrigin[0]=rtcOrigin[0];frameCtx.snapPickOrigin[1]=rtcOrigin[1];frameCtx.snapPickOrigin[2]=rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;frameCtx.snapPickOrigin[0]=0;frameCtx.snapPickOrigin[1]=0;frameCtx.snapPickOrigin[2]=0;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform2fv(this._uVectorA,frameCtx.snapVectorA);gl.uniform2fv(this._uInverseVectorAB,frameCtx.snapInvVectorAB);gl.uniform1i(this._uLayerNumber,frameCtx.snapPickLayerNumber);gl.uniform3fv(this._uCoordinateScaler,coordinateScaler);gl.uniform1i(this._uRenderPass,renderPass);gl.uniform1i(this._uPickInvisible,frameCtx.pickInvisible);gl.uniformMatrix4fv(this._uSceneWorldModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);{var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uSceneWorldModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i343=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3430;var src=[];src.push("#version 300 es");src.push("// DTXTrianglesSnapInitRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 uVectorAB;");src.push("uniform vec2 uInverseVectorAB;");src.push("vec3 positions[3];");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;");src.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("flat out uint vFlags2;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// constants +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uSceneWorldModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i345=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3450;var src=[];src.push("#version 300 es");src.push("// DTXTrianglesSnapInitRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("uniform vec2 uVectorAB;");src.push("uniform vec2 uInverseVectorAB;");src.push("vec3 positions[3];");{src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("vec2 remapClipPos(vec2 clipPos) {");src.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;");src.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;");src.push(" return vec2(x, y);");src.push("}");src.push("flat out vec4 vPickColor;");src.push("out vec4 vWorldPosition;");if(clipping){src.push("flat out uint vFlags2;");}src.push("out highp vec3 relativeToOriginPosition;");src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");src.push("{");// get color @@ -16068,12 +16071,12 @@ src.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(i src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");// when the geometry is not solid, if needed, flip the triangle winding src.push("if (solid != 1u) {");src.push(" if (isPerspectiveMatrix(projMatrix)) {");src.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" viewNormal = -viewNormal;");src.push(" }");src.push(" } else {");src.push(" if (viewNormal.z < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" viewNormal = -viewNormal;");src.push(" }");src.push(" }");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("relativeToOriginPosition = worldPosition.xyz;");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vWorldPosition = worldPosition;");if(clipping){src.push("vFlags2 = flags2.r;");}src.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));");// TODO: Normalized color? See here: //src.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) /255.0;"); -src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// DTXTrianglesSnapInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int uLayerNumber;");src.push("uniform vec3 uCoordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("flat in uint vFlags2;");for(var _i344=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i344 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSnapInitRenderer;}();var tempVec3a$e=math.vec3();var tempVec3b$a=math.vec3();var tempVec3c$8=math.vec3();math.vec3();var tempMat4a$4=math.mat4();/** +src.push("vec4 clipPos = projMatrix * viewPosition;");src.push("float tmp = clipPos.w;");src.push("clipPos.xyzw /= tmp;");src.push("clipPos.xy = remapClipPos(clipPos.xy);");src.push("clipPos.xyzw *= tmp;");{src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// DTXTrianglesSnapInitRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");{src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("uniform int uLayerNumber;");src.push("uniform vec3 uCoordinateScaler;");src.push("in vec4 vWorldPosition;");src.push("flat in vec4 vPickColor;");if(clipping){src.push("flat in uint vFlags2;");for(var _i346=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i346 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}{src.push(" float dx = dFdx(vFragDepth);");src.push(" float dy = dFdy(vFragDepth);");src.push(" float diff = sqrt(dx*dx+dy*dy);");src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;");}src.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);");src.push("vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push("vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push("outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("outPickColor = uvec4(vPickColor);");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesSnapInitRenderer;}();var tempVec3a$e=math.vec3();var tempVec3b$a=math.vec3();var tempVec3c$8=math.vec3();math.vec3();var tempMat4a$4=math.mat4();/** * @private */var DTXTrianglesOcclusionRenderer=/*#__PURE__*/function(){function DTXTrianglesOcclusionRenderer(scene){_classCallCheck(this,DTXTrianglesOcclusionRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesOcclusionRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var viewMatrix=frameCtx.pickViewMatrix||camera.viewMatrix;if(!this._program){this._allocate(dataTextureLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram();}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;if(origin||position[0]!==0||position[1]!==0||position[2]!==0){var rtcOrigin=tempVec3a$e;if(origin){var rotatedOrigin=tempVec3b$a;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$4);rtcCameraEye=tempVec3c$8;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;}gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform1i(this._uRenderPass,renderPass);gl.uniformMatrix4fv(this._uWorldMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uWorldMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i345=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3450;var src=[];src.push("#version 300 es");src.push("// TrianglesDataTextureOcclusionRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uWorldMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i347=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3470;var src=[];src.push("#version 300 es");src.push("// TrianglesDataTextureOcclusionRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.x = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT @@ -16085,13 +16088,13 @@ src.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFl src.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));");src.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));");src.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));");// get color src.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);");src.push("if (color.a == 0u) {");src.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);");// Cull vertex src.push(" return;");src.push("};");src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");// when the geometry is not solid, if needed, flip the triangle winding -src.push("if (solid != 1u) {");src.push(" if (isPerspectiveMatrix(projMatrix)) {");src.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" }");src.push(" } else {");src.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");src.push(" if (viewNormal.z < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" }");src.push(" }");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i346=0;_i346 0.0);");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i347=0;_i347 0.0) { discard; }");src.push(" }");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue +src.push("if (solid != 1u) {");src.push(" if (isPerspectiveMatrix(projMatrix)) {");src.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" }");src.push(" } else {");src.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");src.push(" if (viewNormal.z < 0.0) {");src.push(" position = positions[2 - (gl_VertexID % 3)];");src.push(" }");src.push(" }");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var sectionPlanesState=scene._sectionPlanesState;var clipping=sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTextureColorRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i348=0;_i348 0.0);");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i349=0;_i349 0.0) { discard; }");src.push(" }");}src.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); ");// Occluders are blue src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesOcclusionRenderer;}();var tempVec3a$d=math.vec3();var tempVec3b$9=math.vec3();var tempVec3c$7=math.vec3();math.vec3();var tempMat4a$3=math.mat4();/** * @private */var DTXTrianglesDepthRenderer=/*#__PURE__*/function(){function DTXTrianglesDepthRenderer(scene){_classCallCheck(this,DTXTrianglesDepthRenderer);this._scene=scene;this._allocate();this._hash=this._getHash();}_createClass(DTXTrianglesDepthRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var scene=this._scene;var camera=scene.camera;var model=dataTextureLayer.model;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx,state);}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$d;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3b$9);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(camera.viewMatrix,rtcOrigin,tempMat4a$3);rtcCameraEye=tempVec3c$7;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=camera.viewMatrix;rtcCameraEye=camera.eye;}gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform1i(this._uRenderPass,renderPass);if(scene.logarithmicDepthBufferEnabled){var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPositionsDecodeMatrix=program.getLocation("objectDecodeAndInstanceMatrix");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i348=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3480;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture draw vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out highp vec2 vHighPrecisionZW;");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPositionsDecodeMatrix=program.getLocation("objectDecodeAndInstanceMatrix");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i350=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3500;var src=[];src.push("#version 300 es");src.push("// Triangles dataTexture draw vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out highp vec2 vHighPrecisionZW;");if(clipping){src.push("out vec4 vWorldPosition;");src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// flags.x = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT @@ -16104,21 +16107,21 @@ src.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(i src.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);");src.push("if (color.a == 0u) {");src.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);");// Cull vertex src.push(" return;");src.push("};");// get normal src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");// when the geometry is not solid, if needed, flip the triangle winding -src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("vHighPrecisionZW = gl_Position.zw;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");src.push("in highp vec2 vHighPrecisionZW;");src.push("out vec4 outColor;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i349=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i349 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i350=0,_len76=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i350<_len76;_i350++){src.push("if (sectionPlaneActive"+_i350+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i350+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i350+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");//src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"); +src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}if(clipping){src.push("vWorldPosition = worldPosition;");src.push("vFlags2 = flags2.r;");}src.push("gl_Position = clipPos;");src.push("vHighPrecisionZW = gl_Position.zw;");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// Triangles dataTexture draw fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");src.push("in highp vec2 vHighPrecisionZW;");src.push("out vec4 outColor;");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("flat in uint vFlags2;");for(var _i351=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i351 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i352=0,_len76=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i352<_len76;_i352++){src.push("if (sectionPlaneActive"+_i352+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i352+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i352+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");//src.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"); }src.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;");src.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); ");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesDepthRenderer;}();var tempVec3a$c=math.vec3();var tempVec3b$8=math.vec3();var tempVec3c$6=math.vec3();math.vec3();var tempMat4a$2=math.mat4();/** * @private */var DTXTrianglesNormalsRenderer=/*#__PURE__*/function(){function DTXTrianglesNormalsRenderer(scene){_classCallCheck(this,DTXTrianglesNormalsRenderer);this._scene=scene;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesNormalsRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){return this._scene._sectionPlanesState.getHash();}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var model=dataTextureLayer.model;var scene=model.scene;var camera=scene.camera;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;var viewMatrix=camera.viewMatrix;if(!this._program){this._allocate(dataTextureLayer);if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(dataTextureLayer);}var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$c;if(gotOrigin){var rotatedOrigin=tempVec3b$8;math.transformPoint3(rotationMatrix,origin,rotatedOrigin);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(viewMatrix,rtcOrigin,tempMat4a$2);rtcCameraEye=tempVec3c$6;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=viewMatrix;rtcCameraEye=camera.eye;}gl.uniform1i(this._uRenderPass,renderPass);gl.uniformMatrix4fv(this._uWorldMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);gl.uniformMatrix4fv(this._uViewNormalMatrix,false,camera.viewNormalMatrix);gl.uniformMatrix4fv(this._uWorldNormalMatrix,false,model.worldNormalMatrix);var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0;var src=[];src.push("// Batched geometry normals vertex shader");if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("#extension GL_EXT_frag_depth : enable");}src.push("uniform int renderPass;");src.push("attribute vec3 position;");if(scene.entityOffsetsEnabled){src.push("attribute vec3 offset;");}src.push("attribute vec3 normal;");src.push("attribute vec4 color;");src.push("attribute vec4 flags;");src.push("attribute vec4 flags2;");src.push("uniform mat4 worldMatrix;");src.push("uniform mat4 worldNormalMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform mat4 viewNormalMatrix;");src.push("uniform mat4 objectDecodeAndInstanceMatrix;");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");if(WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("out float vFragDepth;");}src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("varying float isPerspective;");}src.push("vec3 octDecode(vec2 oct) {");src.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));");src.push(" if (v.z < 0.0) {");src.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);");src.push(" }");src.push(" return normalize(v);");src.push("}");if(clipping){src.push("out vec4 vWorldPosition;");src.push("out vec4 vFlags2;");}src.push("out vec3 vViewNormal;");src.push("void main(void) {");// flags.x = NOT_RENDERED | COLOR_OPAQUE | COLOR_TRANSPARENT // renderPass = COLOR_OPAQUE -src.push("if (int(flags.x) != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){if(WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("vFragDepth = 1.0 + clipPos.w;");}else{src.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;");src.push("clipPos.z *= clipPos.w;");}src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("#extension GL_EXT_frag_depth : enable");}src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in vec4 vFlags2;");for(var _i352=0;_i352 0.0);");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesNormalsRenderer;}();var tempVec3a$b=math.vec3();var tempVec3b$7=math.vec3();var tempVec3c$5=math.vec3();math.vec3();math.vec4();var tempMat4a$1=math.mat4();/** +src.push("if (int(flags.x) != renderPass) {");src.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);");src.push(" } else {");src.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");if(scene.entityOffsetsEnabled){src.push(" worldPosition.xyz = worldPosition.xyz + offset;");}src.push(" vec4 viewPosition = viewMatrix * worldPosition; ");src.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); ");src.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);");if(clipping){src.push(" vWorldPosition = worldPosition;");src.push(" vFlags2 = flags2;");}src.push(" vViewNormal = viewNormal;");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){if(WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("vFragDepth = 1.0 + clipPos.w;");}else{src.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;");src.push("clipPos.z *= clipPos.w;");}src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("gl_Position = clipPos;");src.push(" }");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push("#version 300 es");src.push("// Batched geometry normals fragment shader");if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("#extension GL_EXT_frag_depth : enable");}src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}if(clipping){src.push("in vec4 vWorldPosition;");src.push("in vec4 vFlags2;");for(var _i354=0;_i354 0.0);");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var i=0;i 0.0) { discard; }");src.push(" }");}if(scene.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS["EXT_frag_depth"]){src.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); ");src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesNormalsRenderer;}();var tempVec3a$b=math.vec3();var tempVec3b$7=math.vec3();var tempVec3c$5=math.vec3();math.vec3();math.vec4();var tempMat4a$1=math.mat4();/** * @private */var DTXTrianglesPickNormalsFlatRenderer=/*#__PURE__*/function(){function DTXTrianglesPickNormalsFlatRenderer(scene,withSAO){_classCallCheck(this,DTXTrianglesPickNormalsFlatRenderer);this._scene=scene;this._withSAO=withSAO;this._hash=this._getHash();this._allocate();}_createClass(DTXTrianglesPickNormalsFlatRenderer,[{key:"getValid",value:function getValid(){return this._hash===this._getHash();}},{key:"_getHash",value:function _getHash(){var scene=this._scene;return[scene._lightsState.getHash(),scene._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";");}},{key:"drawLayer",value:function drawLayer(frameCtx,dataTextureLayer,renderPass){var scene=this._scene;var camera=scene.camera;var model=dataTextureLayer.model;var gl=scene.canvas.gl;var state=dataTextureLayer._state;var textureState=state.textureState;var origin=dataTextureLayer._state.origin;var position=model.position,rotationMatrix=model.rotationMatrix,rotationMatrixConjugate=model.rotationMatrixConjugate;if(!this._program){this._allocate();if(this.errors){return;}}if(frameCtx.lastProgramId!==this._program.id){frameCtx.lastProgramId=this._program.id;this._bindProgram(frameCtx,state);}textureState.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var rtcViewMatrix;var rtcCameraEye;var gotOrigin=origin[0]!==0||origin[1]!==0||origin[2]!==0;var gotPosition=position[0]!==0||position[1]!==0||position[2]!==0;if(gotOrigin||gotPosition){var rtcOrigin=tempVec3a$b;if(gotOrigin){var rotatedOrigin=math.transformPoint3(rotationMatrix,origin,tempVec3b$7);rtcOrigin[0]=rotatedOrigin[0];rtcOrigin[1]=rotatedOrigin[1];rtcOrigin[2]=rotatedOrigin[2];}else{rtcOrigin[0]=0;rtcOrigin[1]=0;rtcOrigin[2]=0;}rtcOrigin[0]+=position[0];rtcOrigin[1]+=position[1];rtcOrigin[2]+=position[2];rtcViewMatrix=createRTCViewMat(camera.viewMatrix,rtcOrigin,tempMat4a$1);rtcCameraEye=tempVec3c$5;rtcCameraEye[0]=camera.eye[0]-rtcOrigin[0];rtcCameraEye[1]=camera.eye[1]-rtcOrigin[1];rtcCameraEye[2]=camera.eye[2]-rtcOrigin[2];}else{rtcViewMatrix=camera.viewMatrix;// TODO: make pickMatrix rtcCameraEye=camera.eye;}gl.uniform2fv(this._uPickClipPos,frameCtx.pickClipPos);gl.uniform2f(this._uDrawingBufferSize,gl.drawingBufferWidth,gl.drawingBufferHeight);gl.uniformMatrix4fv(this._uSceneModelMatrix,false,rotationMatrixConjugate);gl.uniformMatrix4fv(this._uViewMatrix,false,rtcViewMatrix);gl.uniformMatrix4fv(this._uProjMatrix,false,camera.projMatrix);// TODO: pickProjMatrix gl.uniform3fv(this._uCameraEyeRtc,rtcCameraEye);gl.uniform1i(this._uRenderPass,renderPass);if(scene.logarithmicDepthBufferEnabled){var logDepthBufFC=2.0/(Math.log(frameCtx.pickZFar+1.0)/Math.LN2);gl.uniform1f(this._uLogDepthBufFC,logDepthBufFC);}var numAllocatedSectionPlanes=scene._sectionPlanesState.getNumAllocatedSectionPlanes();var numSectionPlanes=scene._sectionPlanesState.sectionPlanes.length;if(numAllocatedSectionPlanes>0){var sectionPlanes=scene._sectionPlanesState.sectionPlanes;var baseIndex=dataTextureLayer.layerIndex*numSectionPlanes;var renderFlags=model.renderFlags;for(var sectionPlaneIndex=0;sectionPlaneIndex0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8// 8 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices8Bits);}if(state.numIndices16Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16// 16 bits indices );gl.drawArrays(gl.TRIANGLES,0,state.numIndices16Bits);}if(state.numIndices32Bits>0){textureState.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32// 32 bits indices -);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i353=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3530;var src=[];src.push("#version 300 es");src.push("// trianglesDatatextureNormalsRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("uniform vec2 drawingBufferSize;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out vec4 vWorldPosition;");if(clipping){src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants +);gl.drawArrays(gl.TRIANGLES,0,state.numIndices32Bits);}frameCtx.drawElements++;}},{key:"_allocate",value:function _allocate(){var scene=this._scene;var gl=scene.canvas.gl;this._program=new Program(gl,this._buildShader());if(this._program.errors){this.errors=this._program.errors;return;}var program=this._program;this._uRenderPass=program.getLocation("renderPass");this._uPickInvisible=program.getLocation("pickInvisible");this._uPickClipPos=program.getLocation("pickClipPos");this._uDrawingBufferSize=program.getLocation("drawingBufferSize");this._uSceneModelMatrix=program.getLocation("sceneModelMatrix");this._uViewMatrix=program.getLocation("viewMatrix");this._uProjMatrix=program.getLocation("projMatrix");this._uSectionPlanes=[];for(var _i355=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i3550;var src=[];src.push("#version 300 es");src.push("// trianglesDatatextureNormalsRenderer vertex shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("precision highp usampler2D;");src.push("precision highp isampler2D;");src.push("precision highp sampler2D;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("precision mediump usampler2D;");src.push("precision mediump isampler2D;");src.push("precision mediump sampler2D;");src.push("#endif");src.push("uniform int renderPass;");if(scene.entityOffsetsEnabled){src.push("in vec3 offset;");}src.push("uniform mat4 sceneModelMatrix;");src.push("uniform mat4 viewMatrix;");src.push("uniform mat4 projMatrix;");src.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;");src.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;");src.push("uniform highp sampler2D uTexturePerObjectMatrix;");src.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;");src.push("uniform highp usampler2D uTexturePerPolygonIdIndices;");src.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;");src.push("uniform vec3 uCameraEyeRtc;");src.push("vec3 positions[3];");if(scene.logarithmicDepthBufferEnabled){src.push("uniform float logDepthBufFC;");src.push("out float vFragDepth;");src.push("out float isPerspective;");}src.push("uniform vec2 pickClipPos;");src.push("uniform vec2 drawingBufferSize;");src.push("vec4 remapClipPos(vec4 clipPos) {");src.push(" clipPos.xy /= clipPos.w;");src.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;");src.push(" clipPos.xy *= clipPos.w;");src.push(" return clipPos;");src.push("}");src.push("bool isPerspectiveMatrix(mat4 m) {");src.push(" return (m[2][3] == - 1.0);");src.push("}");src.push("out vec4 vWorldPosition;");if(clipping){src.push("flat out uint vFlags2;");}src.push("void main(void) {");// constants src.push("int polygonIndex = gl_VertexID / 3;");// get packed object-id src.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;");src.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;");src.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);");src.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);");// get flags & flags2 src.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);");src.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);");// pickFlag = NOT_RENDERED | PICK @@ -16132,7 +16135,7 @@ src.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(object src.push(" return;");src.push("};");// get normal src.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));");src.push("vec3 position;");src.push("position = positions[gl_VertexID % 3];");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");// when the geometry is not solid, if needed, flip the triangle winding src.push("if (solid != 1u) {");src.push("if (isPerspectiveMatrix(projMatrix)) {");src.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;");// src.push("vColor = vec4(vec3(1, -1, 0)*dot(normalize(position.xyz - uCameraEyeRtcInQuantizedSpace), normal), 1);") -src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("vWorldPosition = worldPosition;");if(clipping){src.push("vFlags2 = flags2.r;");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTexturePickNormalsRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("flat in uint vFlags2;");for(var _i354=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i354 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i355=0,_len77=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i355<_len77;_i355++){src.push("if (sectionPlaneActive"+_i355+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i355+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i355+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesPickNormalsFlatRenderer;}();/** +src.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("viewNormal = -viewNormal;");src.push("}");src.push("} else {");src.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);");src.push("if (viewNormal.z < 0.0) {");src.push("position = positions[2 - (gl_VertexID % 3)];");src.push("}");src.push("}");src.push("}");src.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); ");src.push("vec4 viewPosition = viewMatrix * worldPosition; ");src.push("vec4 clipPos = projMatrix * viewPosition;");if(scene.logarithmicDepthBufferEnabled){src.push("vFragDepth = 1.0 + clipPos.w;");src.push("isPerspective = float (isPerspectiveMatrix(projMatrix));");}src.push("vWorldPosition = worldPosition;");if(clipping){src.push("vFlags2 = flags2.r;");}src.push("gl_Position = remapClipPos(clipPos);");src.push("}");src.push("}");return src;}},{key:"_buildFragmentShader",value:function _buildFragmentShader(){var scene=this._scene;var clipping=scene._sectionPlanesState.getNumAllocatedSectionPlanes()>0;var src=[];src.push('#version 300 es');src.push("// TrianglesDataTexturePickNormalsRenderer fragment shader");src.push("#ifdef GL_FRAGMENT_PRECISION_HIGH");src.push("precision highp float;");src.push("precision highp int;");src.push("#else");src.push("precision mediump float;");src.push("precision mediump int;");src.push("#endif");if(scene.logarithmicDepthBufferEnabled){src.push("in float isPerspective;");src.push("uniform float logDepthBufFC;");src.push("in float vFragDepth;");}src.push("in vec4 vWorldPosition;");if(clipping){src.push("flat in uint vFlags2;");for(var _i356=0,len=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i356 0u;");src.push(" if (clippable) {");src.push(" float dist = 0.0;");for(var _i357=0,_len77=scene._sectionPlanesState.getNumAllocatedSectionPlanes();_i357<_len77;_i357++){src.push("if (sectionPlaneActive"+_i357+") {");src.push(" dist += clamp(dot(-sectionPlaneDir"+_i357+".xyz, vWorldPosition.xyz - sectionPlanePos"+_i357+".xyz), 0.0, 1000.0);");src.push("}");}src.push(" if (dist > 0.0) { ");src.push(" discard;");src.push(" }");src.push("}");}if(scene.logarithmicDepthBufferEnabled){src.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");}src.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );");src.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );");src.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );");src.push(" outNormal = ivec4(worldNormal * float(".concat(math.MAX_INT,"), 1.0);"));src.push("}");return src;}},{key:"webglContextRestored",value:function webglContextRestored(){this._program=null;}},{key:"destroy",value:function destroy(){if(this._program){this._program.destroy();}this._program=null;}}]);return DTXTrianglesPickNormalsFlatRenderer;}();/** * @private */var DTXTrianglesRenderers=/*#__PURE__*/function(){function DTXTrianglesRenderers(scene){_classCallCheck(this,DTXTrianglesRenderers);this._scene=scene;}_createClass(DTXTrianglesRenderers,[{key:"_compile",value:function _compile(){if(this._colorRenderer&&!this._colorRenderer.getValid()){this._colorRenderer.destroy();this._colorRenderer=null;}if(this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()){this._colorRendererWithSAO.destroy();this._colorRendererWithSAO=null;}if(this._flatColorRenderer&&!this._flatColorRenderer.getValid()){this._flatColorRenderer.destroy();this._flatColorRenderer=null;}if(this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()){this._flatColorRendererWithSAO.destroy();this._flatColorRendererWithSAO=null;}if(this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()){this._colorQualityRendererWithSAO.destroy();this._colorQualityRendererWithSAO=null;}if(this._depthRenderer&&!this._depthRenderer.getValid()){this._depthRenderer.destroy();this._depthRenderer=null;}if(this._normalsRenderer&&!this._normalsRenderer.getValid()){this._normalsRenderer.destroy();this._normalsRenderer=null;}if(this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()){this._silhouetteRenderer.destroy();this._silhouetteRenderer=null;}if(this._edgesRenderer&&!this._edgesRenderer.getValid()){this._edgesRenderer.destroy();this._edgesRenderer=null;}if(this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()){this._edgesColorRenderer.destroy();this._edgesColorRenderer=null;}if(this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()){this._pickMeshRenderer.destroy();this._pickMeshRenderer=null;}if(this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()){this._pickDepthRenderer.destroy();this._pickDepthRenderer=null;}if(this._snapRenderer&&!this._snapRenderer.getValid()){this._snapRenderer.destroy();this._snapRenderer=null;}if(this._snapInitRenderer&&!this._snapInitRenderer.getValid()){this._snapInitRenderer.destroy();this._snapInitRenderer=null;}if(this._pickNormalsRenderer&&this._pickNormalsRenderer.getValid()===false){this._pickNormalsRenderer.destroy();this._pickNormalsRenderer=null;}if(this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.getValid()===false){this._pickNormalsFlatRenderer.destroy();this._pickNormalsFlatRenderer=null;}if(this._occlusionRenderer&&this._occlusionRenderer.getValid()===false){this._occlusionRenderer.destroy();this._occlusionRenderer=null;}}},{key:"eagerCreateRenders",value:function eagerCreateRenders(){// Pre-initialize certain renderers that would otherwise be lazy-initialised // on user interaction, such as picking or emphasis, so that there is no delay @@ -16300,15 +16303,15 @@ this.numPortions=numPortions;var textureWidth=512*8;var textureHeight=Math.ceil( // - col5: (packed Uint32 bytes as RGBA) index base offset // - col6: (packed Uint32 bytes as RGBA) edge index base offset // - col7: (packed 4 bytes as RGBA) is-solid flag for objects -var texArray=new Uint8Array(4*textureWidth*textureHeight);dataTextureRamStats.sizeDataColorsAndFlags+=texArray.byteLength;dataTextureRamStats.numberOfTextures++;for(var _i356=0;_i356>24&255,vertexBases[_i356]>>16&255,vertexBases[_i356]>>8&255,vertexBases[_i356]&255],_i356*32+16);// triangles index base offset -texArray.set([indexBaseOffsets[_i356]>>24&255,indexBaseOffsets[_i356]>>16&255,indexBaseOffsets[_i356]>>8&255,indexBaseOffsets[_i356]&255],_i356*32+20);// edge index base offset -texArray.set([edgeIndexBaseOffsets[_i356]>>24&255,edgeIndexBaseOffsets[_i356]>>16&255,edgeIndexBaseOffsets[_i356]>>8&255,edgeIndexBaseOffsets[_i356]&255],_i356*32+24);// is-solid flag -texArray.set([solid[_i356]?1:0,0,0,0],_i356*32+28);}var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texStorage2D(gl.TEXTURE_2D,1,gl.RGBA8UI,textureWidth,textureHeight);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,textureWidth,textureHeight,gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,texArray,0);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindTexture(gl.TEXTURE_2D,null);return new BindableDataTexture(gl,texture,textureWidth,textureHeight,texArray);}/** +texArray.set([vertexBases[_i358]>>24&255,vertexBases[_i358]>>16&255,vertexBases[_i358]>>8&255,vertexBases[_i358]&255],_i358*32+16);// triangles index base offset +texArray.set([indexBaseOffsets[_i358]>>24&255,indexBaseOffsets[_i358]>>16&255,indexBaseOffsets[_i358]>>8&255,indexBaseOffsets[_i358]&255],_i358*32+20);// edge index base offset +texArray.set([edgeIndexBaseOffsets[_i358]>>24&255,edgeIndexBaseOffsets[_i358]>>16&255,edgeIndexBaseOffsets[_i358]>>8&255,edgeIndexBaseOffsets[_i358]&255],_i358*32+24);// is-solid flag +texArray.set([solid[_i358]?1:0,0,0,0],_i358*32+28);}var texture=gl.createTexture();gl.bindTexture(gl.TEXTURE_2D,texture);gl.texStorage2D(gl.TEXTURE_2D,1,gl.RGBA8UI,textureWidth,textureHeight);gl.texSubImage2D(gl.TEXTURE_2D,0,0,0,textureWidth,textureHeight,gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,texArray,0);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.NEAREST);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);gl.bindTexture(gl.TEXTURE_2D,null);return new BindableDataTexture(gl,texture,textureWidth,textureHeight,texArray);}/** * This will generate a texture for all object offsets. * * @param {WebGL2RenderingContext} gl @@ -16329,8 +16332,8 @@ texArray.set([solid[_i356]?1:0,0,0,0],_i356*32+28);}var texture=gl.createTexture * @returns {BindableDataTexture} */},{key:"createTextureForInstancingMatrices",value:function createTextureForInstancingMatrices(gl,instanceMatrices){var numMatrices=instanceMatrices.length;if(numMatrices===0){throw"num instance matrices===0";}// in one row we can fit 512 matrices var textureWidth=512*4;var textureHeight=Math.ceil(numMatrices/(textureWidth/4));var texArray=new Float32Array(4*textureWidth*textureHeight);// dataTextureRamStats.sizeDataPositionDecodeMatrices += texArray.byteLength; -dataTextureRamStats.numberOfTextures++;for(var _i357=0;_i357} positionsArrays Arrays of quantized positions in the layer * @param lenPositions @@ -16392,7 +16395,7 @@ texArray.set(positionDecodeMatrices[_i358],_i358*16);}var texture=gl.createTextu * - a number of rows R where R*1024 is just >= than the number of vertices (positions / 3) * * @returns {BindableDataTexture} - */},{key:"createTextureForPositions",value:function createTextureForPositions(gl,positionsArrays,lenPositions){var numVertices=lenPositions/3;var textureWidth=4096;var textureHeight=Math.ceil(numVertices/textureWidth);if(textureHeight===0){throw"texture height===0";}var texArraySize=textureWidth*textureHeight*3;var texArray=new Uint16Array(texArraySize);dataTextureRamStats.sizeDataTexturePositions+=texArray.byteLength;dataTextureRamStats.numberOfTextures++;for(var _i365=0,j=0,len=positionsArrays.length;_i365} portionIdsArray * @@ -16432,7 +16435,7 @@ this._numVisibleLayerPortions=0;this._numTransparentLayerPortions=0;this._numXRa * The axis-aligned World-space boundary of this TrianglesDataTextureLayer's positions. */this._aabb=math.collapseAABB3();this.aabbDirty=true;/** * The number of updates in the current frame; - */this._numUpdatesInFrame=0;this._finalized=false;}_createClass(DTXTrianglesLayer,[{key:"aabb",get:function get(){if(this.aabbDirty){math.collapseAABB3(this._aabb);for(var _i366=0,len=this._meshes.length;_i3660){var _numIndices4=bucketGeometry.numTriangles*3;var indicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){indicesPortionIdBuffer=buffer.perTriangleNumberPortionId8Bits;state.numIndices8Bits+=_numIndices4;dataTextureRamStats.totalPolygons8Bits+=bucketGeometry.numTriangles;}else if(bucketGeometry.numVertices<=1<<16){indicesPortionIdBuffer=buffer.perTriangleNumberPortionId16Bits;state.numIndices16Bits+=_numIndices4;dataTextureRamStats.totalPolygons16Bits+=bucketGeometry.numTriangles;}else{indicesPortionIdBuffer=buffer.perTriangleNumberPortionId32Bits;state.numIndices32Bits+=_numIndices4;dataTextureRamStats.totalPolygons32Bits+=bucketGeometry.numTriangles;}dataTextureRamStats.totalPolygons+=bucketGeometry.numTriangles;for(var _i367=0;_i3670){var numEdgeIndices=bucketGeometry.numEdges*2;var edgeIndicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId8Bits;state.numEdgeIndices8Bits+=numEdgeIndices;dataTextureRamStats.totalEdges8Bits+=bucketGeometry.numEdges;}else if(bucketGeometry.numVertices<=1<<16){edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId16Bits;state.numEdgeIndices16Bits+=numEdgeIndices;dataTextureRamStats.totalEdges16Bits+=bucketGeometry.numEdges;}else{edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId32Bits;state.numEdgeIndices32Bits+=numEdgeIndices;dataTextureRamStats.totalEdges32Bits+=bucketGeometry.numEdges;}dataTextureRamStats.totalEdges+=bucketGeometry.numEdges;for(var _i368=0;_i3680){var _numIndices4=bucketGeometry.numTriangles*3;var indicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){indicesPortionIdBuffer=buffer.perTriangleNumberPortionId8Bits;state.numIndices8Bits+=_numIndices4;dataTextureRamStats.totalPolygons8Bits+=bucketGeometry.numTriangles;}else if(bucketGeometry.numVertices<=1<<16){indicesPortionIdBuffer=buffer.perTriangleNumberPortionId16Bits;state.numIndices16Bits+=_numIndices4;dataTextureRamStats.totalPolygons16Bits+=bucketGeometry.numTriangles;}else{indicesPortionIdBuffer=buffer.perTriangleNumberPortionId32Bits;state.numIndices32Bits+=_numIndices4;dataTextureRamStats.totalPolygons32Bits+=bucketGeometry.numTriangles;}dataTextureRamStats.totalPolygons+=bucketGeometry.numTriangles;for(var _i369=0;_i3690){var numEdgeIndices=bucketGeometry.numEdges*2;var edgeIndicesPortionIdBuffer;if(bucketGeometry.numVertices<=1<<8){edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId8Bits;state.numEdgeIndices8Bits+=numEdgeIndices;dataTextureRamStats.totalEdges8Bits+=bucketGeometry.numEdges;}else if(bucketGeometry.numVertices<=1<<16){edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId16Bits;state.numEdgeIndices16Bits+=numEdgeIndices;dataTextureRamStats.totalEdges16Bits+=bucketGeometry.numEdges;}else{edgeIndicesPortionIdBuffer=buffer.perEdgeNumberPortionId32Bits;state.numEdgeIndices32Bits+=numEdgeIndices;dataTextureRamStats.totalEdges32Bits+=bucketGeometry.numEdges;}dataTextureRamStats.totalEdges+=bucketGeometry.numEdges;for(var _i370=0;_i370=MAX_OBJECT_UPDATES_IN_FRAME_WITHOUT_BATCHED_UPDATE){this._beginDeferredFlags();// Subsequent flags updates now deferred }console.info("_subPortionSetColor write through");gl.bindTexture(gl.TEXTURE_2D,textureState.texturePerObjectColorsAndFlags._texture);gl.texSubImage2D(gl.TEXTURE_2D,0,// level @@ -16526,7 +16529,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"setTransparent",value:function setTransparent(portionId,flags,transparent){if(transparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}else{this._numTransparentLayerPortions--;this.model.numTransparentLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"_setFlags",value:function _setFlags(portionId,flags,transparent){var deferred=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i370=0,len=subPortionIds.length;_i3703&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);var edges=!!(flags&ENTITY_FLAGS.EDGES);var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);// Color +}},{key:"setTransparent",value:function setTransparent(portionId,flags,transparent){if(transparent){this._numTransparentLayerPortions++;this.model.numTransparentLayerPortions++;}else{this._numTransparentLayerPortions--;this.model.numTransparentLayerPortions--;}this._setFlags(portionId,flags,transparent);}},{key:"_setFlags",value:function _setFlags(portionId,flags,transparent){var deferred=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i372=0,len=subPortionIds.length;_i3723&&arguments[3]!==undefined?arguments[3]:false;if(!this._finalized){throw"Not finalized";}var visible=!!(flags&ENTITY_FLAGS.VISIBLE);var xrayed=!!(flags&ENTITY_FLAGS.XRAYED);var highlighted=!!(flags&ENTITY_FLAGS.HIGHLIGHTED);var selected=!!(flags&ENTITY_FLAGS.SELECTED);var edges=!!(flags&ENTITY_FLAGS.EDGES);var pickable=!!(flags&ENTITY_FLAGS.PICKABLE);var culled=!!(flags&ENTITY_FLAGS.CULLED);// Color var f0;if(!visible||culled||xrayed||highlighted&&!this.model.scene.highlightMaterial.glowThrough||selected&&!this.model.scene.selectedMaterial.glowThrough){f0=RENDER_PASSES.NOT_RENDERED;}else{if(transparent){f0=RENDER_PASSES.COLOR_TRANSPARENT;}else{f0=RENDER_PASSES.COLOR_OPAQUE;}}// Silhouette var f1;if(!visible||culled){f1=RENDER_PASSES.NOT_RENDERED;}else if(selected){f1=RENDER_PASSES.SILHOUETTE_SELECTED;}else if(highlighted){f1=RENDER_PASSES.SILHOUETTE_HIGHLIGHTED;}else if(xrayed){f1=RENDER_PASSES.SILHOUETTE_XRAYED;}else{f1=RENDER_PASSES.NOT_RENDERED;}// Edges var f2=0;if(!visible||culled){f2=RENDER_PASSES.NOT_RENDERED;}else if(selected){f2=RENDER_PASSES.EDGES_SELECTED;}else if(highlighted){f2=RENDER_PASSES.EDGES_HIGHLIGHTED;}else if(xrayed){f2=RENDER_PASSES.EDGES_XRAYED;}else if(edges){if(transparent){f2=RENDER_PASSES.EDGES_COLOR_TRANSPARENT;}else{f2=RENDER_PASSES.EDGES_COLOR_OPAQUE;}}else{f2=RENDER_PASSES.NOT_RENDERED;}// Pick @@ -16538,7 +16541,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"_setDeferredFlags",value:function _setDeferredFlags(){}},{key:"_setFlags2",value:function _setFlags2(portionId,flags){var deferred=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i371=0,len=subPortionIds.length;_i3712&&arguments[2]!==undefined?arguments[2]:false;if(!this._finalized){throw"Not finalized";}var clippable=!!(flags&ENTITY_FLAGS.CLIPPABLE)?255:0;var textureState=this._dtxState;var gl=this.model.scene.canvas.gl;tempUint8Array4[0]=clippable;tempUint8Array4[1]=0;tempUint8Array4[2]=1;tempUint8Array4[3]=2;// object flags2 +}},{key:"_setDeferredFlags",value:function _setDeferredFlags(){}},{key:"_setFlags2",value:function _setFlags2(portionId,flags){var deferred=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i373=0,len=subPortionIds.length;_i3732&&arguments[2]!==undefined?arguments[2]:false;if(!this._finalized){throw"Not finalized";}var clippable=!!(flags&ENTITY_FLAGS.CLIPPABLE)?255:0;var textureState=this._dtxState;var gl=this.model.scene.canvas.gl;tempUint8Array4[0]=clippable;tempUint8Array4[1]=0;tempUint8Array4[2]=1;tempUint8Array4[3]=2;// object flags2 textureState.texturePerObjectColorsAndFlags._textureData.set(tempUint8Array4,subPortionId*32+12);if(this._deferredSetFlagsActive||deferred){// console.log("_subPortionSetFlags2 set flags defer"); this._deferredSetFlagsDirty=true;return;}if(++this._numUpdatesInFrame>=MAX_OBJECT_UPDATES_IN_FRAME_WITHOUT_BATCHED_UPDATE){this._beginDeferredFlags();// Subsequent flags updates now deferred }gl.bindTexture(gl.TEXTURE_2D,textureState.texturePerObjectColorsAndFlags._texture);gl.texSubImage2D(gl.TEXTURE_2D,0,// level @@ -16547,7 +16550,7 @@ Math.floor(subPortionId/512),// yoffset 1,// width 1,//height gl.RGBA_INTEGER,gl.UNSIGNED_BYTE,tempUint8Array4);// gl.bindTexture (gl.TEXTURE_2D, null); -}},{key:"_setDeferredFlags2",value:function _setDeferredFlags2(){}},{key:"setOffset",value:function setOffset(portionId,offset){var subPortionIds=this._portionToSubPortionsMap[portionId];for(var _i372=0,len=subPortionIds.length;_i3720&&arguments[0]!==undefined?arguments[0]:4;_classCallCheck(this,WorkerPool$1);this.pool=pool;this.queue=[];this.workers=[];this.workersResolve=[];this.workerStatus=0;}_createClass(WorkerPool$1,[{key:"_initWorker",value:function _initWorker(workerId){if(!this.workers[workerId]){var worker=this.workerCreator();worker.addEventListener('message',this._onMessage.bind(this,workerId));this.workers[workerId]=worker;}}},{key:"_getIdleWorker",value:function _getIdleWorker(){for(var _i378=0;_i3780&&arguments[0]!==undefined?arguments[0]:4;_classCallCheck(this,WorkerPool$1);this.pool=pool;this.queue=[];this.workers=[];this.workersResolve=[];this.workerStatus=0;}_createClass(WorkerPool$1,[{key:"_initWorker",value:function _initWorker(workerId){if(!this.workers[workerId]){var worker=this.workerCreator();worker.addEventListener('message',this._onMessage.bind(this,workerId));this.workers[workerId]=worker;}}},{key:"_getIdleWorker",value:function _getIdleWorker(){for(var _i380=0;_i380=maxPositions){return;}seqInit=new Uint32Array(maxPositions);for(var _i382=0;_i382=maxPositions){return;}seqInit=new Uint32Array(maxPositions);for(var _i384=0;_i384 the uniquified positionsCompressed; 1 and 2 => the remapped edges and edgeIndices arrays - */function uniquifyPositions(mesh){var _positions=mesh.positionsCompressed;var _indices=mesh.indices;var _edgeIndices=mesh.edgeIndices;setMaxNumberOfPositions(_positions.length/3);var seq=seqInit.slice(0,_positions.length/3);var remappings=seqInit.slice(0,_positions.length/3);comparePositions=_positions;seq.sort(compareVertex);var uniqueIdx=0;remappings[seq[0]]=0;for(var _i383=1,len=seq.length;_i383>bitsPerBucket;}seq.sort(compareBuckets);var sortedIndices=new Int32Array(indices.length);for(var _i389=0,_len82=seq.length;_i389<_len82;_i389++){sortedIndices[_i389*3+0]=indices[seq[_i389]*3+0];sortedIndices[_i389*3+1]=indices[seq[_i389]*3+1];sortedIndices[_i389*3+2]=indices[seq[_i389]*3+2];}return sortedIndices;}var compareEdgeIndices=null;function compareIndices(a,b){var retVal=compareEdgeIndices[a*2]-compareEdgeIndices[b*2];if(retVal!==0){return retVal;}return compareEdgeIndices[a*2+1]-compareEdgeIndices[b*2+1];}function preSortEdgeIndices(edgeIndices){if((edgeIndices||[]).length===0){return[];}var seq=new Int32Array(edgeIndices.length/2);for(var _i390=0,len=seq.length;_i390edgeIndices[_i391+1]){var tmp=edgeIndices[_i391];edgeIndices[_i391]=edgeIndices[_i391+1];edgeIndices[_i391+1]=tmp;}}compareEdgeIndices=new Int32Array(edgeIndices);seq.sort(compareIndices);var sortedEdgeIndices=new Int32Array(edgeIndices.length);for(var _i392=0,_len84=seq.length;_i392<_len84;_i392++){sortedEdgeIndices[_i392*2+0]=edgeIndices[seq[_i392]*2+0];sortedEdgeIndices[_i392*2+1]=edgeIndices[seq[_i392]*2+1];}return sortedEdgeIndices;}/** + **/var MAX_RE_BUCKET_FAN_OUT=8;var bucketsForIndices=null;function compareBuckets(a,b){var aa=a*3;var bb=b*3;var aa1,aa2,aa3,bb1,bb2,bb3;var minBucketA=Math.min(aa1=bucketsForIndices[aa],aa2=bucketsForIndices[aa+1],aa3=bucketsForIndices[aa+2]);var minBucketB=Math.min(bb1=bucketsForIndices[bb],bb2=bucketsForIndices[bb+1],bb3=bucketsForIndices[bb+2]);if(minBucketA!==minBucketB){return minBucketA-minBucketB;}var maxBucketA=Math.max(aa1,aa2,aa3);var maxBucketB=Math.max(bb1,bb2,bb3);if(maxBucketA!==maxBucketB){return maxBucketA-maxBucketB;}return 0;}function preSortIndices(indices,bitsPerBucket){var seq=new Int32Array(indices.length/3);for(var _i389=0,len=seq.length;_i389>bitsPerBucket;}seq.sort(compareBuckets);var sortedIndices=new Int32Array(indices.length);for(var _i391=0,_len82=seq.length;_i391<_len82;_i391++){sortedIndices[_i391*3+0]=indices[seq[_i391]*3+0];sortedIndices[_i391*3+1]=indices[seq[_i391]*3+1];sortedIndices[_i391*3+2]=indices[seq[_i391]*3+2];}return sortedIndices;}var compareEdgeIndices=null;function compareIndices(a,b){var retVal=compareEdgeIndices[a*2]-compareEdgeIndices[b*2];if(retVal!==0){return retVal;}return compareEdgeIndices[a*2+1]-compareEdgeIndices[b*2+1];}function preSortEdgeIndices(edgeIndices){if((edgeIndices||[]).length===0){return[];}var seq=new Int32Array(edgeIndices.length/2);for(var _i392=0,len=seq.length;_i392edgeIndices[_i393+1]){var tmp=edgeIndices[_i393];edgeIndices[_i393]=edgeIndices[_i393+1];edgeIndices[_i393+1]=tmp;}}compareEdgeIndices=new Int32Array(edgeIndices);seq.sort(compareIndices);var sortedEdgeIndices=new Int32Array(edgeIndices.length);for(var _i394=0,_len84=seq.length;_i394<_len84;_i394++){sortedEdgeIndices[_i394*2+0]=edgeIndices[seq[_i394]*2+0];sortedEdgeIndices[_i394*2+1]=edgeIndices[seq[_i394]*2+1];}return sortedEdgeIndices;}/** * @param {{positionsCompressed: number[], indices: number[], edgeIndices: number[]}} mesh * @param {number} bitsPerBucket * @param {boolean} checkResult * * @returns {{positionsCompressed: number[], indices: number[], edgeIndices: number[]}[]} */function rebucketPositions(mesh,bitsPerBucket){var checkResult=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;var positionsCompressed=mesh.positionsCompressed||[];var indices=preSortIndices(mesh.indices||[],bitsPerBucket);var edgeIndices=preSortEdgeIndices(mesh.edgeIndices||[]);function edgeSearch(el0,el1){// Code adapted from https://stackoverflow.com/questions/22697936/binary-search-in-javascript -if(el0>el1){var tmp=el0;el0=el1;el1=tmp;}function compare_fn(a,b){if(a!==el0){return el0-a;}if(b!==el1){return el1-b;}return 0;}var m=0;var n=(edgeIndices.length>>1)-1;while(m<=n){var k=n+m>>1;var cmp=compare_fn(edgeIndices[k*2],edgeIndices[k*2+1]);if(cmp>0){m=k+1;}else if(cmp<0){n=k-1;}else{return k;}}return-m-1;}var alreadyOutputEdgeIndices=new Int32Array(edgeIndices.length/2);alreadyOutputEdgeIndices.fill(0);var numPositions=positionsCompressed.length/3;if(numPositions>(1<currentBucket.maxNumPositions){currentBucket=addEmptyBucket();}if(currentBucket.bucketNumber>MAX_RE_BUCKET_FAN_OUT){return[mesh];}if(bucketIndicesRemap[ii0]===-1){bucketIndicesRemap[ii0]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii0*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii0*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii0*3+2]);}if(bucketIndicesRemap[ii1]===-1){bucketIndicesRemap[ii1]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii1*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii1*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii1*3+2]);}if(bucketIndicesRemap[ii2]===-1){bucketIndicesRemap[ii2]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii2*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii2*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii2*3+2]);}currentBucket.indices.push(bucketIndicesRemap[ii0]);currentBucket.indices.push(bucketIndicesRemap[ii1]);currentBucket.indices.push(bucketIndicesRemap[ii2]);// Check possible edge1 -var edgeIndex=void 0;if((edgeIndex=edgeSearch(ii0,ii1))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}if((edgeIndex=edgeSearch(ii0,ii2))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}if((edgeIndex=edgeSearch(ii1,ii2))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}}var prevBytesPerIndex=bitsPerBucket/8*2;var newBytesPerIndex=bitsPerBucket/8;var originalSize=positionsCompressed.length*2+(indices.length+edgeIndices.length)*prevBytesPerIndex;var newSize=0;var newPositions=-positionsCompressed.length/3;buckets.forEach(function(bucket){newSize+=bucket.positionsCompressed.length*2+(bucket.indices.length+bucket.edgeIndices.length)*newBytesPerIndex;newPositions+=bucket.positionsCompressed.length/3;});if(newSize>originalSize){return[mesh];}if(checkResult){doCheckResult(buckets,mesh);}return buckets;}function doCheckResult(buckets,mesh){var meshDict={};var edgesDict={};var edgeIndicesCount=0;buckets.forEach(function(bucket){var indices=bucket.indices;var edgeIndices=bucket.edgeIndices;var positionsCompressed=bucket.positionsCompressed;for(var _i394=0,len=indices.length;_i394el1){var tmp=el0;el0=el1;el1=tmp;}function compare_fn(a,b){if(a!==el0){return el0-a;}if(b!==el1){return el1-b;}return 0;}var m=0;var n=(edgeIndices.length>>1)-1;while(m<=n){var k=n+m>>1;var cmp=compare_fn(edgeIndices[k*2],edgeIndices[k*2+1]);if(cmp>0){m=k+1;}else if(cmp<0){n=k-1;}else{return k;}}return-m-1;}var alreadyOutputEdgeIndices=new Int32Array(edgeIndices.length/2);alreadyOutputEdgeIndices.fill(0);var numPositions=positionsCompressed.length/3;if(numPositions>(1<currentBucket.maxNumPositions){currentBucket=addEmptyBucket();}if(currentBucket.bucketNumber>MAX_RE_BUCKET_FAN_OUT){return[mesh];}if(bucketIndicesRemap[ii0]===-1){bucketIndicesRemap[ii0]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii0*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii0*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii0*3+2]);}if(bucketIndicesRemap[ii1]===-1){bucketIndicesRemap[ii1]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii1*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii1*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii1*3+2]);}if(bucketIndicesRemap[ii2]===-1){bucketIndicesRemap[ii2]=currentBucket.numPositions++;currentBucket.positionsCompressed.push(positionsCompressed[ii2*3]);currentBucket.positionsCompressed.push(positionsCompressed[ii2*3+1]);currentBucket.positionsCompressed.push(positionsCompressed[ii2*3+2]);}currentBucket.indices.push(bucketIndicesRemap[ii0]);currentBucket.indices.push(bucketIndicesRemap[ii1]);currentBucket.indices.push(bucketIndicesRemap[ii2]);// Check possible edge1 +var edgeIndex=void 0;if((edgeIndex=edgeSearch(ii0,ii1))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}if((edgeIndex=edgeSearch(ii0,ii2))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}if((edgeIndex=edgeSearch(ii1,ii2))>=0){if(alreadyOutputEdgeIndices[edgeIndex]===0){alreadyOutputEdgeIndices[edgeIndex]=1;currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2]]);currentBucket.edgeIndices.push(bucketIndicesRemap[edgeIndices[edgeIndex*2+1]]);}}}var prevBytesPerIndex=bitsPerBucket/8*2;var newBytesPerIndex=bitsPerBucket/8;var originalSize=positionsCompressed.length*2+(indices.length+edgeIndices.length)*prevBytesPerIndex;var newSize=0;var newPositions=-positionsCompressed.length/3;buckets.forEach(function(bucket){newSize+=bucket.positionsCompressed.length*2+(bucket.indices.length+bucket.edgeIndices.length)*newBytesPerIndex;newPositions+=bucket.positionsCompressed.length/3;});if(newSize>originalSize){return[mesh];}if(checkResult){doCheckResult(buckets,mesh);}return buckets;}function doCheckResult(buckets,mesh){var meshDict={};var edgesDict={};var edgeIndicesCount=0;buckets.forEach(function(bucket){var indices=bucket.indices;var edgeIndices=bucket.edgeIndices;var positionsCompressed=bucket.positionsCompressed;for(var _i396=0,len=indices.length;_i3960){var meshes=childTransform._meshes;for(var j=0,lenj=meshes.length;j0){var _meshes=this._meshes;for(var _j3=0,_lenj2=_meshes.length;_j3<_lenj2;_j3++){_meshes[_j3]._transformDirty();}}}},{key:"_buildWorldMatrix",value:function _buildWorldMatrix(){var localMatrix=this.matrix;if(!this._parentTransform){for(var _i398=0,len=localMatrix.length;_i3980){var meshes=childTransform._meshes;for(var j=0,lenj=meshes.length;j0){var _meshes=this._meshes;for(var _j3=0,_lenj2=_meshes.length;_j3<_lenj2;_j3++){_meshes[_j3]._transformDirty();}}}},{key:"_buildWorldMatrix",value:function _buildWorldMatrix(){var localMatrix=this.matrix;if(!this._parentTransform){for(var _i400=0,len=localMatrix.length;_i4001&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,SceneModel);_this78=_super114.call(this,owner,cfg);_this78._dtxEnabled=_this78.scene.dtxEnabled&&cfg.dtxEnabled!==false;_this78._enableVertexWelding=false;// Not needed for most objects, and very expensive, so disabled + * @param {Number} [cfg.renderOrder=0] Specifies the rendering order for this SceneModel. This is used to control the order in which + * SceneModels are drawn when they have transparent objects, to give control over the order in which those objects are blended within the transparent + * render pass. + */function SceneModel(owner){var _this78;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,SceneModel);_this78=_super114.call(this,owner,cfg);_this78.renderOrder=cfg.renderOrder||0;_this78._dtxEnabled=_this78.scene.dtxEnabled&&cfg.dtxEnabled!==false;_this78._enableVertexWelding=false;// Not needed for most objects, and very expensive, so disabled _this78._enableIndexBucketing=false;// Until fixed: https://github.com/xeokit/xeokit-sdk/issues/1204 _this78._vboBatchingLayerScratchMemory=getScratchMemory();_this78._textureTranscoder=cfg.textureTranscoder||getKTX2TextureTranscoder(_this78.scene.viewer);_this78._maxGeometryBatchSize=cfg.maxGeometryBatchSize;_this78._aabb=math.collapseAABB3();_this78._aabbDirty=true;_this78._quantizationRanges={};_this78._vboInstancingLayers={};_this78._vboBatchingLayers={};_this78._dtxLayers={};_this78._meshList=[];_this78.layerList=[];// For GL state efficiency when drawing, InstancingLayers are in first part, BatchingLayers are in second _this78._entityList=[];_this78._geometries={};_this78._dtxBuckets={};// Geometries with optimizations used for data texture representation @@ -18295,7 +18301,7 @@ var defaultColorTexture=new SceneModelTexture({id:DEFAULT_COLOR_TEXTURE_ID,textu * This is used for RTC view matrix management in renderers. * * @type {Number[]} - */},{key:"rotationMatrixConjugate",get:function get(){if(this._matrixDirty){this._rebuildMatrices();}return this._worldRotationMatrixConjugate;}},{key:"_setWorldMatrixDirty",value:function _setWorldMatrixDirty(){this._matrixDirty=true;this._aabbDirty=true;}},{key:"_transformDirty",value:function _transformDirty(){this._matrixDirty=true;this._aabbDirty=true;this.scene._aabbDirty=true;}},{key:"_sceneModelDirty",value:function _sceneModelDirty(){this.scene._aabbDirty=true;this._aabbDirty=true;this.scene._aabbDirty=true;this._matrixDirty=true;for(var _i400=0,len=this._entityList.length;_i4000){cfg.colorsCompressed=new Uint8Array(cfg.colorsCompressed);}else if(cfg.colors&&cfg.colors.length>0){var colors=cfg.colors;var colorsCompressed=new Uint8Array(colors.length);for(var _i414=0,_len86=colors.length;_i414<_len86;_i414++){colorsCompressed[_i414]=colors[_i414]*255;}cfg.colorsCompressed=colorsCompressed;}if(!cfg.buckets&&!cfg.edgeIndices&&(cfg.primitive==="triangles"||cfg.primitive==="solid"||cfg.primitive==="surface")){if(cfg.positions){cfg.edgeIndices=buildEdgeIndices(cfg.positions,cfg.indices,null,5.0);}else{cfg.edgeIndices=buildEdgeIndices(cfg.positionsCompressed,cfg.indices,cfg.positionsDecodeMatrix,2.0);}}if(cfg.uv){var bounds=geometryCompressionUtils.getUVBounds(cfg.uv);var result=geometryCompressionUtils.compressUVs(cfg.uv,bounds.min,bounds.max);cfg.uvCompressed=result.quantized;cfg.uvDecodeMatrix=result.decodeMatrix;}else if(cfg.uvCompressed){cfg.uvCompressed=new Uint16Array(cfg.uvCompressed);cfg.uvDecodeMatrix=new Float64Array(cfg.uvDecodeMatrix);}if(cfg.normals){// HACK + */},{key:"createGeometry",value:function createGeometry(cfg){if(cfg.id===undefined||cfg.id===null){this.error("[createGeometry] Config missing: id");return;}if(this._geometries[cfg.id]){this.error("[createGeometry] Geometry already created: "+cfg.id);return;}if(cfg.primitive===undefined||cfg.primitive===null){cfg.primitive="triangles";}if(cfg.primitive!=="points"&&cfg.primitive!=="lines"&&cfg.primitive!=="triangles"&&cfg.primitive!=="solid"&&cfg.primitive!=="surface"){this.error("[createGeometry] Unsupported value for 'primitive': '".concat(cfg.primitive,"' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'."));return;}if(!cfg.positions&&!cfg.positionsCompressed&&!cfg.buckets){this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets");return null;}if(cfg.positionsCompressed&&!cfg.positionsDecodeMatrix&&!cfg.positionsDecodeBoundary){this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')");return null;}if(cfg.positionsDecodeMatrix&&cfg.positionsDecodeBoundary){this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')");return null;}if(cfg.uvCompressed&&!cfg.uvDecodeMatrix){this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')");return null;}if(!cfg.buckets&&!cfg.indices&&(cfg.primitive==="triangles"||cfg.primitive==="solid"||cfg.primitive==="surface")){var numPositions=(cfg.positions||cfg.positionsCompressed).length/3;cfg.indices=this._createDefaultIndices(numPositions);}if(!cfg.buckets&&!cfg.indices&&cfg.primitive!=="points"){this.error("[createGeometry] Param expected: indices (required for '".concat(cfg.primitive,"' primitive type)"));return null;}if(cfg.positionsDecodeBoundary){cfg.positionsDecodeMatrix=createPositionsDecodeMatrix(cfg.positionsDecodeBoundary,math.mat4());}if(cfg.positions){var aabb=math.collapseAABB3();cfg.positionsDecodeMatrix=math.mat4();math.expandAABB3Points3(aabb,cfg.positions);cfg.positionsCompressed=quantizePositions(cfg.positions,aabb,cfg.positionsDecodeMatrix);cfg.aabb=aabb;}else if(cfg.positionsCompressed){var _aabb=math.collapseAABB3();cfg.positionsDecodeMatrix=new Float64Array(cfg.positionsDecodeMatrix);cfg.positionsCompressed=new Uint16Array(cfg.positionsCompressed);math.expandAABB3Points3(_aabb,cfg.positionsCompressed);geometryCompressionUtils.decompressAABB(_aabb,cfg.positionsDecodeMatrix);cfg.aabb=_aabb;}else if(cfg.buckets){var _aabb2=math.collapseAABB3();this._dtxBuckets[cfg.id]=cfg.buckets;for(var _i415=0,len=cfg.buckets.length;_i4150){cfg.colorsCompressed=new Uint8Array(cfg.colorsCompressed);}else if(cfg.colors&&cfg.colors.length>0){var colors=cfg.colors;var colorsCompressed=new Uint8Array(colors.length);for(var _i416=0,_len86=colors.length;_i416<_len86;_i416++){colorsCompressed[_i416]=colors[_i416]*255;}cfg.colorsCompressed=colorsCompressed;}if(!cfg.buckets&&!cfg.edgeIndices&&(cfg.primitive==="triangles"||cfg.primitive==="solid"||cfg.primitive==="surface")){if(cfg.positions){cfg.edgeIndices=buildEdgeIndices(cfg.positions,cfg.indices,null,5.0);}else{cfg.edgeIndices=buildEdgeIndices(cfg.positionsCompressed,cfg.indices,cfg.positionsDecodeMatrix,2.0);}}if(cfg.uv){var bounds=geometryCompressionUtils.getUVBounds(cfg.uv);var result=geometryCompressionUtils.compressUVs(cfg.uv,bounds.min,bounds.max);cfg.uvCompressed=result.quantized;cfg.uvDecodeMatrix=result.decodeMatrix;}else if(cfg.uvCompressed){cfg.uvCompressed=new Uint16Array(cfg.uvCompressed);cfg.uvDecodeMatrix=new Float64Array(cfg.uvDecodeMatrix);}if(cfg.normals){// HACK cfg.normals=null;}this._geometries[cfg.id]=cfg;this._numTriangles+=cfg.indices?Math.round(cfg.indices.length/3):0;this.numGeometries++;}/** * Creates a texture within this SceneModel. * @@ -18697,7 +18703,7 @@ if(cfg.matrix){cfg.meshMatrix=cfg.matrix;}else if(cfg.scale||cfg.rotation||cfg.p cfg.type=DTX;// NPR cfg.color=cfg.color?new Uint8Array([Math.floor(cfg.color[0]*255),Math.floor(cfg.color[1]*255),Math.floor(cfg.color[2]*255)]):defaultCompressedColor;cfg.opacity=cfg.opacity!==undefined&&cfg.opacity!==null?Math.floor(cfg.opacity*255):255;// RTC if(cfg.positions){var rtcCenter=math.vec3();var rtcPositions=[];var rtcNeeded=worldToRTCPositions(cfg.positions,rtcPositions,rtcCenter);if(rtcNeeded){cfg.positions=rtcPositions;cfg.origin=math.addVec3(cfg.origin,rtcCenter,rtcCenter);}}// COMPRESSION -if(cfg.positions){var aabb=math.collapseAABB3();cfg.positionsDecodeMatrix=math.mat4();math.expandAABB3Points3(aabb,cfg.positions);cfg.positionsCompressed=quantizePositions(cfg.positions,aabb,cfg.positionsDecodeMatrix);cfg.aabb=aabb;}else if(cfg.positionsCompressed){var _aabb3=math.collapseAABB3();math.expandAABB3Points3(_aabb3,cfg.positionsCompressed);geometryCompressionUtils.decompressAABB(_aabb3,cfg.positionsDecodeMatrix);cfg.aabb=_aabb3;}if(cfg.buckets){var _aabb4=math.collapseAABB3();for(var _i415=0,len=cfg.buckets.length;_i415>24&0xFF;var b=pickId>>16&0xFF;var g=pickId>>8&0xFF;var r=pickId&0xFF;cfg.pickColor=new Uint8Array([r,g,b,a]);// Quantized pick color -cfg.solid=cfg.primitive==="solid";mesh.origin=math.vec3(cfg.origin);switch(cfg.type){case DTX:mesh.layer=this._getDTXLayer(cfg);mesh.aabb=cfg.aabb;break;case VBO_BATCHED:mesh.layer=this._getVBOBatchingLayer(cfg);mesh.aabb=cfg.aabb;break;case VBO_INSTANCED:mesh.layer=this._getVBOInstancingLayer(cfg);mesh.aabb=cfg.aabb;break;}if(cfg.transform){cfg.meshMatrix=cfg.transform.worldMatrix;}mesh.portionId=mesh.layer.createPortion(mesh,cfg);this._meshes[cfg.id]=mesh;this._unusedMeshes[cfg.id]=mesh;this._meshList.push(mesh);return mesh;}},{key:"_getNumPrimitives",value:function _getNumPrimitives(cfg){var countIndices=0;var primitive=cfg.geometry?cfg.geometry.primitive:cfg.primitive;switch(primitive){case"triangles":case"solid":case"surface":switch(cfg.type){case DTX:for(var _i416=0,len=cfg.buckets.length;_i416>>0).toString(16);return hashString;}},{key:"_getVBOInstancingLayer",value:function _getVBOInstancingLayer(cfg){var model=this;var origin=cfg.origin;var textureSetId=cfg.textureSetId||"-";var geometryId=cfg.geometryId;var layerId="".concat(Math.round(origin[0]),".").concat(Math.round(origin[1]),".").concat(Math.round(origin[2]),".").concat(textureSetId,".").concat(geometryId);var vboInstancingLayer=this._vboInstancingLayers[layerId];if(vboInstancingLayer){return vboInstancingLayer;}var textureSet=cfg.textureSet;var geometry=cfg.geometry;while(!vboInstancingLayer){switch(geometry.primitive){case"triangles":// console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer=new VBOInstancingTrianglesLayer({model:model,textureSet:textureSet,geometry:geometry,origin:origin,layerIndex:0,solid:false});break;case"solid":// console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); vboInstancingLayer=new VBOInstancingTrianglesLayer({model:model,textureSet:textureSet,geometry:geometry,origin:origin,layerIndex:0,solid:true});break;case"surface":// console.info(`[SceneModel ${this.id}]: creating TrianglesInstancingLayer`); @@ -18782,7 +18788,7 @@ vboInstancingLayer=new VBOInstancingPointsLayer({model:model,textureSet:textureS * @param {Boolean} [cfg.selected=false] Indicates if the SceneModelEntity is initially selected. Selected appearance is configured by {@link SceneModel#selectedMaterial}. * @param {Boolean} [cfg.edges=false] Indicates if the SceneModelEntity's edges are initially emphasized. Edges appearance is configured by {@link SceneModel#edgeMaterial}. * @returns {SceneModelEntity} The new SceneModelEntity. - */},{key:"createEntity",value:function createEntity(cfg){if(cfg.id===undefined){cfg.id=math.createUUID();}else if(this.scene.components[cfg.id]){this.error("Scene already has a Component with this ID: ".concat(cfg.id," - will assign random ID"));cfg.id=math.createUUID();}if(cfg.meshIds===undefined){this.error("Config missing: meshIds");return;}var flags=0;if(this._visible&&cfg.visible!==false){flags=flags|ENTITY_FLAGS.VISIBLE;}if(this._pickable&&cfg.pickable!==false){flags=flags|ENTITY_FLAGS.PICKABLE;}if(this._culled&&cfg.culled!==false){flags=flags|ENTITY_FLAGS.CULLED;}if(this._clippable&&cfg.clippable!==false){flags=flags|ENTITY_FLAGS.CLIPPABLE;}if(this._collidable&&cfg.collidable!==false){flags=flags|ENTITY_FLAGS.COLLIDABLE;}if(this._edges&&cfg.edges!==false){flags=flags|ENTITY_FLAGS.EDGES;}if(this._xrayed&&cfg.xrayed!==false){flags=flags|ENTITY_FLAGS.XRAYED;}if(this._highlighted&&cfg.highlighted!==false){flags=flags|ENTITY_FLAGS.HIGHLIGHTED;}if(this._selected&&cfg.selected!==false){flags=flags|ENTITY_FLAGS.SELECTED;}cfg.flags=flags;this._createEntity(cfg);}},{key:"_createEntity",value:function _createEntity(cfg){var meshes=[];for(var _i420=0,len=cfg.meshIds.length;_i420b.sortId){return 1;}return 0;});for(var _i424=0,_len91=this.layerList.length;_i424<_len91;_i424++){var _layer=this.layerList[_i424];_layer.layerIndex=_i424;}this.glRedraw();this.scene._aabbDirty=true;this._viewMatrixDirty=true;this._matrixDirty=true;this._aabbDirty=true;this._setWorldMatrixDirty();this._sceneModelDirty();this.position=this._position;}/** @private */},{key:"stateSortCompare",value:function stateSortCompare(drawable1,drawable2){}/** @private */},{key:"rebuildRenderFlags",value:function rebuildRenderFlags(){this.renderFlags.reset();this._updateRenderFlagsVisibleLayers();if(this.renderFlags.numLayers>0&&this.renderFlags.numVisibleLayers===0){this.renderFlags.culled=true;return;}this._updateRenderFlags();}/** + */},{key:"finalize",value:function finalize(){if(this.destroyed){return;}this._createDummyEntityForUnusedMeshes();for(var _i423=0,len=this.layerList.length;_i423b.sortId){return 1;}return 0;});for(var _i426=0,_len91=this.layerList.length;_i426<_len91;_i426++){var _layer=this.layerList[_i426];_layer.layerIndex=_i426;}this.glRedraw();this.scene._aabbDirty=true;this._viewMatrixDirty=true;this._matrixDirty=true;this._aabbDirty=true;this._setWorldMatrixDirty();this._sceneModelDirty();this.position=this._position;}/** @private */},{key:"stateSortCompare",value:function stateSortCompare(drawable1,drawable2){}/** @private */},{key:"rebuildRenderFlags",value:function rebuildRenderFlags(){this.renderFlags.reset();this._updateRenderFlagsVisibleLayers();if(this.renderFlags.numLayers>0&&this.renderFlags.numVisibleLayers===0){this.renderFlags.culled=true;return;}this._updateRenderFlags();}/** * @private - */},{key:"_updateRenderFlagsVisibleLayers",value:function _updateRenderFlagsVisibleLayers(){var renderFlags=this.renderFlags;renderFlags.numLayers=this.layerList.length;renderFlags.numVisibleLayers=0;for(var layerIndex=0,len=this.layerList.length;layerIndex0){var entityId="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn("Creating dummy SceneModelEntity \"".concat(entityId,"\" for unused SceneMeshes: [").concat(unusedMeshIds.join(","),"]"));this.createEntity({id:entityId,meshIds:unusedMeshIds,isObject:true});}this._unusedMeshes={};}},{key:"_getActiveSectionPlanesForLayer",value:function _getActiveSectionPlanesForLayer(layer){var renderFlags=this.renderFlags;var sectionPlanes=this.scene._sectionPlanesState.sectionPlanes;var numSectionPlanes=sectionPlanes.length;var baseIndex=layer.layerIndex*numSectionPlanes;if(numSectionPlanes>0){for(var _i425=0;_i4250){renderFlags.colorTransparent=true;}if(this.numXRayedLayerPortions>0){var xrayMaterial=this.scene.xrayMaterial._state;if(xrayMaterial.fill){if(xrayMaterial.fillAlpha<1.0){renderFlags.xrayedSilhouetteTransparent=true;}else{renderFlags.xrayedSilhouetteOpaque=true;}}if(xrayMaterial.edges){if(xrayMaterial.edgeAlpha<1.0){renderFlags.xrayedEdgesTransparent=true;}else{renderFlags.xrayedEdgesOpaque=true;}}}if(this.numEdgesLayerPortions>0){var edgeMaterial=this.scene.edgeMaterial._state;if(edgeMaterial.edges){renderFlags.edgesOpaque=this.numTransparentLayerPortions0){renderFlags.edgesTransparent=true;}}}if(this.numSelectedLayerPortions>0){var selectedMaterial=this.scene.selectedMaterial._state;if(selectedMaterial.fill){if(selectedMaterial.fillAlpha<1.0){renderFlags.selectedSilhouetteTransparent=true;}else{renderFlags.selectedSilhouetteOpaque=true;}}if(selectedMaterial.edges){if(selectedMaterial.edgeAlpha<1.0){renderFlags.selectedEdgesTransparent=true;}else{renderFlags.selectedEdgesOpaque=true;}}}if(this.numHighlightedLayerPortions>0){var highlightMaterial=this.scene.highlightMaterial._state;if(highlightMaterial.fill){if(highlightMaterial.fillAlpha<1.0){renderFlags.highlightedSilhouetteTransparent=true;}else{renderFlags.highlightedSilhouetteOpaque=true;}}if(highlightMaterial.edges){if(highlightMaterial.edgeAlpha<1.0){renderFlags.highlightedEdgesTransparent=true;}else{renderFlags.highlightedEdgesOpaque=true;}}}}// -------------- RENDERING --------------------------------------------------------------------------------------- -/** @private */},{key:"drawColorOpaque",value:function drawColorOpaque(frameCtx){var renderFlags=this.renderFlags;for(var _i426=0,len=renderFlags.visibleLayers.length;_i4260){var entityId="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn("Creating dummy SceneModelEntity \"".concat(entityId,"\" for unused SceneMeshes: [").concat(unusedMeshIds.join(","),"]"));this.createEntity({id:entityId,meshIds:unusedMeshIds,isObject:true});}this._unusedMeshes={};}},{key:"_getActiveSectionPlanesForLayer",value:function _getActiveSectionPlanesForLayer(layer){var renderFlags=this.renderFlags;var sectionPlanes=this.scene._sectionPlanesState.sectionPlanes;var numSectionPlanes=sectionPlanes.length;var baseIndex=layer.layerIndex*numSectionPlanes;if(numSectionPlanes>0){for(var _i427=0;_i4270){renderFlags.colorTransparent=true;}if(this.numXRayedLayerPortions>0){var xrayMaterial=this.scene.xrayMaterial._state;if(xrayMaterial.fill){if(xrayMaterial.fillAlpha<1.0){renderFlags.xrayedSilhouetteTransparent=true;}else{renderFlags.xrayedSilhouetteOpaque=true;}}if(xrayMaterial.edges){if(xrayMaterial.edgeAlpha<1.0){renderFlags.xrayedEdgesTransparent=true;}else{renderFlags.xrayedEdgesOpaque=true;}}}if(this.numEdgesLayerPortions>0){var edgeMaterial=this.scene.edgeMaterial._state;if(edgeMaterial.edges){renderFlags.edgesOpaque=this.numTransparentLayerPortions0){renderFlags.edgesTransparent=true;}}}if(this.numSelectedLayerPortions>0){var selectedMaterial=this.scene.selectedMaterial._state;if(selectedMaterial.fill){if(selectedMaterial.fillAlpha<1.0){renderFlags.selectedSilhouetteTransparent=true;}else{renderFlags.selectedSilhouetteOpaque=true;}}if(selectedMaterial.edges){if(selectedMaterial.edgeAlpha<1.0){renderFlags.selectedEdgesTransparent=true;}else{renderFlags.selectedEdgesOpaque=true;}}}if(this.numHighlightedLayerPortions>0){var highlightMaterial=this.scene.highlightMaterial._state;if(highlightMaterial.fill){if(highlightMaterial.fillAlpha<1.0){renderFlags.highlightedSilhouetteTransparent=true;}else{renderFlags.highlightedSilhouetteOpaque=true;}}if(highlightMaterial.edges){if(highlightMaterial.edgeAlpha<1.0){renderFlags.highlightedEdgesTransparent=true;}else{renderFlags.highlightedEdgesOpaque=true;}}}}// -------------- RENDERING --------------------------------------------------------------------------------------- +/** @private */},{key:"drawColorOpaque",value:function drawColorOpaque(frameCtx,layerList){var renderFlags=this.renderFlags;for(var _i428=0,len=renderFlags.visibleLayers.length;_i428 { + */},{key:"destroy",value:function destroy(){for(var layerId in this._vboBatchingLayers){if(this._vboBatchingLayers.hasOwnProperty(layerId)){this._vboBatchingLayers[layerId].destroy();}}this._vboBatchingLayers={};for(var _layerId in this._vboInstancingLayers){if(this._vboInstancingLayers.hasOwnProperty(_layerId)){this._vboInstancingLayers[_layerId].destroy();}}this._vboInstancingLayers={};this.scene.camera.off(this._onCameraViewMatrix);this.scene.off(this._onTick);for(var _i448=0,len=this.layerList.length;_i448 { // geometry.destroy(); // }); this._geometries={};this._dtxBuckets={};this._textures={};this._textureSets={};this._meshes={};this._entities={};this.scene._aabbDirty=true;if(this._isModel){this.scene._deregisterModel(this);}putScratchMemory();_get(_getPrototypeOf(SceneModel.prototype),"destroy",this).call(this);}}]);return SceneModel;}(Component);/** @@ -18904,7 +18910,7 @@ var _uniquifyPositions=uniquifyPositions({positionsCompressed:geometry.positions * @param {Number[]} [cfg.color=[0,0,0]] The color of this ````LineSet````. This is both emissive and diffuse. * @param {Boolean} [cfg.visible=true] Indicates whether or not this ````LineSet```` is visible. * @param {Number} [cfg.opacity=1.0] ````LineSet````'s initial opacity factor. - */function LineSet(owner){var _this80;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,LineSet);_this80=_super115.call(this,owner,cfg);_this80._positions=cfg.positions||[];if(cfg.indices){_this80._indices=cfg.indices;}else{_this80._indices=[];for(var _i448=0,len=_this80._positions.length/3-1;_i4481&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,LineSet);_this80=_super115.call(this,owner,cfg);_this80._positions=cfg.positions||[];if(cfg.indices){_this80._indices=cfg.indices;}else{_this80._indices=[];for(var _i450=0,len=_this80._positions.length/3-1;_i4501&&arguments[1]!==undefined?arguments[1]:{};if(!bcfViewpoint){return;}var viewer=this.viewer;var scene=viewer.scene;var camera=scene.camera;var rayCast=options.rayCast!==false;var immediate=options.immediate!==false;var reset=options.reset!==false;var realWorldOffset=scene.realWorldOffset;var reverseClippingPlanes=options.reverseClippingPlanes===true;scene.clearSectionPlanes();if(bcfViewpoint.clipping_planes&&bcfViewpoint.clipping_planes.length>0){bcfViewpoint.clipping_planes.forEach(function(e){var pos=xyzObjectToArray(e.location,tempVec3$5);var dir=xyzObjectToArray(e.direction,tempVec3$5);if(reverseClippingPlanes){math.negateVec3(dir);}math.subVec3(pos,realWorldOffset);if(camera.yUp){pos=ZToY(pos);dir=ZToY(dir);}new SectionPlane(scene,{pos:pos,dir:dir});});}scene.clearLines();if(bcfViewpoint.lines&&bcfViewpoint.lines.length>0){var positions=[];var indices=[];var _i451=0;bcfViewpoint.lines.forEach(function(e){if(!e.start_point){return;}if(!e.end_point){return;}positions.push(e.start_point.x);positions.push(e.start_point.y);positions.push(e.start_point.z);positions.push(e.end_point.x);positions.push(e.end_point.y);positions.push(e.end_point.z);indices.push(_i451++);indices.push(_i451++);});new LineSet(scene,{positions:positions,indices:indices,clippable:false,collidable:true});}scene.clearBitmaps();if(bcfViewpoint.bitmaps&&bcfViewpoint.bitmaps.length>0){bcfViewpoint.bitmaps.forEach(function(e){var bitmap_type=e.bitmap_type||"jpg";// "jpg" | "png" + */},{key:"setViewpoint",value:function setViewpoint(bcfViewpoint){var _this83=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!bcfViewpoint){return;}var viewer=this.viewer;var scene=viewer.scene;var camera=scene.camera;var rayCast=options.rayCast!==false;var immediate=options.immediate!==false;var reset=options.reset!==false;var realWorldOffset=scene.realWorldOffset;var reverseClippingPlanes=options.reverseClippingPlanes===true;scene.clearSectionPlanes();if(bcfViewpoint.clipping_planes&&bcfViewpoint.clipping_planes.length>0){bcfViewpoint.clipping_planes.forEach(function(e){var pos=xyzObjectToArray(e.location,tempVec3$5);var dir=xyzObjectToArray(e.direction,tempVec3$5);if(reverseClippingPlanes){math.negateVec3(dir);}math.subVec3(pos,realWorldOffset);if(camera.yUp){pos=ZToY(pos);dir=ZToY(dir);}new SectionPlane(scene,{pos:pos,dir:dir});});}scene.clearLines();if(bcfViewpoint.lines&&bcfViewpoint.lines.length>0){var positions=[];var indices=[];var _i453=0;bcfViewpoint.lines.forEach(function(e){if(!e.start_point){return;}if(!e.end_point){return;}positions.push(e.start_point.x);positions.push(e.start_point.y);positions.push(e.start_point.z);positions.push(e.end_point.x);positions.push(e.end_point.y);positions.push(e.end_point.z);indices.push(_i453++);indices.push(_i453++);});new LineSet(scene,{positions:positions,indices:indices,clippable:false,collidable:true});}scene.clearBitmaps();if(bcfViewpoint.bitmaps&&bcfViewpoint.bitmaps.length>0){bcfViewpoint.bitmaps.forEach(function(e){var bitmap_type=e.bitmap_type||"jpg";// "jpg" | "png" var bitmap_data=e.bitmap_data;// base64 var location=xyzObjectToArray(e.location,tempVec3a$9);var normal=xyzObjectToArray(e.normal,tempVec3b$6);var up=xyzObjectToArray(e.up,tempVec3c$4);var height=e.height||1;if(!bitmap_type){return;}if(!bitmap_data){return;}if(!location){return;}if(!normal){return;}if(!up){return;}if(camera.yUp){location=ZToY(location);normal=ZToY(normal);up=ZToY(up);}new Bitmap(scene,{src:bitmap_data,type:bitmap_type,pos:location,normal:normal,up:up,clippable:false,collidable:true,height:height});});}if(reset){scene.setObjectsXRayed(scene.xrayedObjectIds,false);scene.setObjectsHighlighted(scene.highlightedObjectIds,false);scene.setObjectsSelected(scene.selectedObjectIds,false);}if(bcfViewpoint.components){if(bcfViewpoint.components.visibility){if(!bcfViewpoint.components.visibility.default_visibility){scene.setObjectsVisible(scene.objectIds,false);if(bcfViewpoint.components.visibility.exceptions){bcfViewpoint.components.visibility.exceptions.forEach(function(component){return _this83._withBCFComponent(options,component,function(entity){return entity.visible=true;});});}}else{scene.setObjectsVisible(scene.objectIds,true);if(bcfViewpoint.components.visibility.exceptions){bcfViewpoint.components.visibility.exceptions.forEach(function(component){return _this83._withBCFComponent(options,component,function(entity){return entity.visible=false;});});}}var view_setup_hints=bcfViewpoint.components.visibility.view_setup_hints;if(view_setup_hints){if(view_setup_hints.spaces_visible===false){scene.setObjectsVisible(viewer.metaScene.getObjectIDsByType("IfcSpace"),false);}if(view_setup_hints.spaces_translucent!==undefined){scene.setObjectsXRayed(viewer.metaScene.getObjectIDsByType("IfcSpace"),true);}if(view_setup_hints.space_boundaries_visible!==undefined);if(view_setup_hints.openings_visible===false){scene.setObjectsVisible(viewer.metaScene.getObjectIDsByType("IfcOpening"),true);}if(view_setup_hints.space_boundaries_translucent!==undefined);if(view_setup_hints.openings_translucent!==undefined){scene.setObjectsXRayed(viewer.metaScene.getObjectIDsByType("IfcOpening"),true);}}}if(bcfViewpoint.components.selection){scene.setObjectsSelected(scene.selectedObjectIds,false);bcfViewpoint.components.selection.forEach(function(component){return _this83._withBCFComponent(options,component,function(entity){return entity.selected=true;});});}if(bcfViewpoint.components.translucency){scene.setObjectsXRayed(scene.xrayedObjectIds,false);bcfViewpoint.components.translucency.forEach(function(component){return _this83._withBCFComponent(options,component,function(entity){return entity.xrayed=true;});});}if(bcfViewpoint.components.coloring){bcfViewpoint.components.coloring.forEach(function(coloring){var color=coloring.color;var alpha=0;var alphaDefined=false;if(color.length===8){alpha=parseInt(color.substring(0,2),16)/256;if(alpha<=1.0&&alpha>=0.95){alpha=1.0;}color=color.substring(2);alphaDefined=true;}var colorize=[parseInt(color.substring(0,2),16)/256,parseInt(color.substring(2,4),16)/256,parseInt(color.substring(4,6),16)/256];coloring.components.map(function(component){return _this83._withBCFComponent(options,component,function(entity){entity.colorize=colorize;if(alphaDefined){entity.opacity=alpha;}});});});}}if(bcfViewpoint.perspective_camera||bcfViewpoint.orthogonal_camera){var eye;var look;var up;var projection;if(bcfViewpoint.perspective_camera){eye=xyzObjectToArray(bcfViewpoint.perspective_camera.camera_view_point,tempVec3$5);look=xyzObjectToArray(bcfViewpoint.perspective_camera.camera_direction,tempVec3$5);up=xyzObjectToArray(bcfViewpoint.perspective_camera.camera_up_vector,tempVec3$5);camera.perspective.fov=bcfViewpoint.perspective_camera.field_of_view;projection="perspective";}else{eye=xyzObjectToArray(bcfViewpoint.orthogonal_camera.camera_view_point,tempVec3$5);look=xyzObjectToArray(bcfViewpoint.orthogonal_camera.camera_direction,tempVec3$5);up=xyzObjectToArray(bcfViewpoint.orthogonal_camera.camera_up_vector,tempVec3$5);camera.ortho.scale=bcfViewpoint.orthogonal_camera.view_to_world_scale;projection="ortho";}math.subVec3(eye,realWorldOffset);if(camera.yUp){eye=ZToY(eye);look=ZToY(look);up=ZToY(up);}if(rayCast){var hit=scene.pick({pickSurface:true,// <<------ This causes picking to find the intersection point on the entity origin:eye,direction:look});look=hit?hit.worldPos:math.addVec3(eye,look,tempVec3$5);}else{look=math.addVec3(eye,look,tempVec3$5);}if(immediate){camera.eye=eye;camera.look=look;camera.up=up;camera.projection=projection;}else{viewer.cameraFlight.flyTo({eye:eye,look:look,up:up,duration:options.duration,projection:projection});}}}},{key:"_withBCFComponent",value:function _withBCFComponent(options,component,callback){var viewer=this.viewer;var scene=viewer.scene;if(component.authoring_tool_id&&component.originating_system===this.originatingSystem){var id=component.authoring_tool_id;var entity=scene.objects[id];if(entity){callback(entity);return;}if(options.updateCompositeObjects){var metaObject=viewer.metaScene.metaObjects[id];if(metaObject){scene.withObjects(viewer.metaScene.getObjectIDsInSubtree(id),callback);return;}}}if(component.ifc_guid){var originalSystemId=component.ifc_guid;var _entity2=scene.objects[originalSystemId];if(_entity2){callback(_entity2);return;}if(options.updateCompositeObjects){var _metaObject=viewer.metaScene.metaObjects[originalSystemId];if(_metaObject){scene.withObjects(viewer.metaScene.getObjectIDsInSubtree(originalSystemId),callback);return;}}Object.keys(scene.models).forEach(function(modelId){var id=math.globalizeObjectId(modelId,originalSystemId);var entity=scene.objects[id];if(entity){callback(entity);return;}if(options.updateCompositeObjects){var _metaObject2=viewer.metaScene.metaObjects[id];if(_metaObject2){scene.withObjects(viewer.metaScene.getObjectIDsInSubtree(id),callback);}}});}}/** @@ -19320,7 +19326,7 @@ this._wp[10]=this._originWorld[2];this._wp[11]=1.0;this._wp[12]=this._targetWorl // this._yAxisLabel.setVisible(this.axisVisible && this.yAxisVisible); // this._zAxisLabel.setVisible(this.axisVisible && this.zAxisVisible); // this._lengthLabel.setVisible(false); -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=false;}}},{key:"_isSliced",value:function _isSliced(positions){var sectionPlanes=this.scene._sectionPlanesState.sectionPlanes;for(var _i452=0,len=sectionPlanes.length;_i4521&&arguments[1]!==undefined?arguments[1]:[];return msg.replace(/\{\{|\}\}|\{(\d+)\}/g,function(m,n){if(m==="{{"){return"{";}if(m==="}}"){return"}";}return args[n];});}/** +}}}]);return LocaleService;}();function resolvePath$1(key,json){if(json[key]){return json[key];}var parts=key.split(".");var obj=json;for(var _i457=0,len=parts.length;obj&&_i4571&&arguments[1]!==undefined?arguments[1]:[];return msg.replace(/\{\{|\}\}|\{(\d+)\}/g,function(m,n){if(m==="{{"){return"{";}if(m==="}}"){return"}";}return args[n];});}/** * @desc Abstract base class for curve classes. */var Curve=/*#__PURE__*/function(_Component32){_inherits(Curve,_Component32);var _super123=_createSuper(Curve);/** * @constructor @@ -20808,7 +20814,7 @@ comparison=arcLengths[i]-targetArcLength;if(comparison<0){low=i+1;}else if(compa * Adds multiple frames to this CameraPath, each frame specified as a set of values for eye, look and up vectors at a given time instant. * * @param {{t:Number, eye:Object, look:Object, up: Object}[]} frames Frames to add to this CameraPath. - */},{key:"addFrames",value:function addFrames(frames){var frame;for(var _i456=0,len=frames.length;_i456>_i459;}return x+1;}/** + */,set:function set(castsShadow){castsShadow=!!castsShadow;if(this._state.castsShadow===castsShadow){return;}this._state.castsShadow=castsShadow;this._shadowViewMatrixDirty=true;this.glRedraw();}},{key:"destroy",value:function destroy(){var camera=this.scene.camera;var canvas=this.scene.canvas;camera.off(this._onCameraViewMatrix);camera.off(this._onCameraProjMatrix);canvas.off(this._onCanvasBoundary);_get(_getPrototypeOf(PointLight.prototype),"destroy",this).call(this);this._state.destroy();if(this._shadowRenderBuf){this._shadowRenderBuf.destroy();}this.scene._lightDestroyed(this);this.glRedraw();}}]);return PointLight;}(Light);function ensureImageSizePowerOfTwo(image){if(!isPowerOfTwo(image.width)||!isPowerOfTwo(image.height)){var _canvas5=document.createElement("canvas");_canvas5.width=nextHighestPowerOfTwo(image.width);_canvas5.height=nextHighestPowerOfTwo(image.height);var ctx=_canvas5.getContext("2d");ctx.drawImage(image,0,0,image.width,image.height,0,0,_canvas5.width,_canvas5.height);image=_canvas5;}return image;}function isPowerOfTwo(x){return(x&x-1)===0;}function nextHighestPowerOfTwo(x){--x;for(var _i461=1;_i461<32;_i461<<=1){x=x|x>>_i461;}return x+1;}/** * @desc A cube texture map. */var CubeTexture=/*#__PURE__*/function(_Component37){_inherits(CubeTexture,_Component37);var _super130=_createSuper(CubeTexture);/** * @constructor @@ -21660,7 +21666,7 @@ if(!self._shadowProjMatrix){self._shadowProjMatrix=math.identityMat4();}var _can // this._state.texture.setImage(this._images, this._state); // this._state.texture.setProps(this._state); // } else -if(this._src){this._loadSrc(this._src);}}},{key:"_loadSrc",value:function _loadSrc(src){var self=this;var gl=this.scene.canvas.gl;this._images=[];var loadFailed=false;var numLoaded=0;var _loop3=function _loop3(_i460){var image=new Image();image.onload=function(){var _image=image;var index=_i460;return function(){if(loadFailed){return;}_image=ensureImageSizePowerOfTwo(_image);self._images[index]=_image;numLoaded++;if(numLoaded===6){var texture=self._state.texture;if(!texture){texture=new Texture2D({gl:gl,target:gl.TEXTURE_CUBE_MAP});self._state.texture=texture;}texture.setImage(self._images,self._state);self.fire("loaded",self._src,false);self.glRedraw();}};}();image.onerror=function(){loadFailed=true;};image.src=src[_i460];};for(var _i460=0;_i460look dist var camera=scene.camera;math.subVec3(camera.eye,camera.look,[]);controllers.cameraFlight.flyTo({aabb:aabb});// TODO: Option to back off to fit AABB in view }else{// Fly to fit target boundary in view controllers.cameraFlight.flyTo({aabb:aabb});}};canvas.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){if(!(configs.active&&configs.pointerEnabled)){return;}if(states.longTouchTimeout!==null){clearTimeout(states.longTouchTimeout);states.longTouchTimeout=null;}var touches=e.touches;var changedTouches=e.changedTouches;touchStartTime=Date.now();if(touches.length===1&&changedTouches.length===1){tapStartTime=touchStartTime;getCanvasPosFromEvent(touches[0],tapStartPos);var rightClickClientX=tapStartPos[0];var rightClickClientY=tapStartPos[1];var rightClickPageX=touches[0].pageX;var rightClickPageY=touches[0].pageY;states.longTouchTimeout=setTimeout(function(){controllers.cameraControl.fire("rightClick",{// For context menus -pagePos:[Math.round(rightClickPageX),Math.round(rightClickPageY)],canvasPos:[Math.round(rightClickClientX),Math.round(rightClickClientY)],event:e},true);states.longTouchTimeout=null;},configs.longTapTimeout);}else{tapStartTime=-1;}while(activeTouches.length-1&¤tTime-tapStartTime-1&&tapStartTime-lastTapTime1&&arguments[1]!==undefined?arguments[1]:{};if(this.finalized){throw"MetaScene already finalized - can't add more data";}this._globalizeIDs(metaModelData,options);var metaScene=this.metaScene;var propertyLookup=metaModelData.properties;// Create global Property Sets -if(metaModelData.propertySets){for(var _i473=0,len=metaModelData.propertySets.length;_i4730&&arguments[0]!==undefined?arguments[0]:{};var needFinishSnapshot=!this._snapshotBegun;var resize=params.width!==undefined&¶ms.height!==undefined;var canvas=this.scene.canvas.canvas;var saveWidth=canvas.clientWidth;var saveHeight=canvas.clientHeight;var width=params.width?Math.floor(params.width):canvas.width;var height=params.height?Math.floor(params.height):canvas.height;if(resize){canvas.width=width;canvas.height=height;}if(!this._snapshotBegun){this.beginSnapshot({width:width,height:height});}if(!params.includeGizmos){this.sendToPlugins("snapshotStarting");// Tells plugins to hide things that shouldn't be in snapshot -}var captured={};for(var _i490=0,len=this._plugins.length;_i4900&&_args[0]!==undefined?_args[0]:{};// We use gl.readPixels to get the WebGL canvas snapshot in a new + */},{key:"getSnapshotWithPlugins",value:function(){var _getSnapshotWithPlugins=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(){var params,needFinishSnapshot,resize,canvas,saveWidth,saveHeight,snapshotWidth,snapshotHeight,snapshotCanvas,pluginToCapture,pluginContainerElements,_i493,len,plugin,containerElement,_i494,_len101,_containerElement,format,_args=arguments;return _regeneratorRuntime().wrap(function _callee$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:params=_args.length>0&&_args[0]!==undefined?_args[0]:{};// We use gl.readPixels to get the WebGL canvas snapshot in a new // HTMLCanvas element, scaled to the target snapshot size, then // use html2canvas to render each plugin's container element into // that HTMLCanvas. Finally, we save the HTMLCanvas to a bitmap. @@ -24692,22 +24698,22 @@ doublePickFlyTo:true});this._plugins=[];/** // canvas ourselves, in order to allow the Viewer to render the // right amount of pixels, for a sharper image. needFinishSnapshot=!this._snapshotBegun;resize=params.width!==undefined&¶ms.height!==undefined;canvas=this.scene.canvas.canvas;saveWidth=canvas.clientWidth;saveHeight=canvas.clientHeight;snapshotWidth=params.width?Math.floor(params.width):canvas.width;snapshotHeight=params.height?Math.floor(params.height):canvas.height;if(resize){canvas.width=snapshotWidth;canvas.height=snapshotHeight;}if(!this._snapshotBegun){this.beginSnapshot();}if(!params.includeGizmos){this.sendToPlugins("snapshotStarting");// Tells plugins to hide things that shouldn't be in snapshot -}this.scene._renderer.renderSnapshot();snapshotCanvas=this.scene._renderer.readSnapshotAsCanvas();if(resize){canvas.width=saveWidth;canvas.height=saveHeight;this.scene.glRedraw();}pluginToCapture={};pluginContainerElements=[];for(_i491=0,len=this._plugins.length;_i4911&&arguments[1]!==undefined?arguments[1]:true;var transfers=arguments.length>2?arguments[2]:undefined;var transfersSet=transfers||new Set();if(!object);else if(isTransferable(object)){transfersSet.add(object);}else if(isTransferable(object.buffer)){transfersSet.add(object.buffer);}else if(ArrayBuffer.isView(object));else if(recursive&&_typeof(object)==='object'){for(var key in object){getTransferList(object[key],recursive,transfersSet);}}return transfers===undefined?Array.from(transfersSet):[];}function isTransferable(object){if(!object){return false;}if(object instanceof ArrayBuffer){return true;}if(typeof MessagePort!=='undefined'&&object instanceof MessagePort){return true;}if(typeof ImageBitmap!=='undefined'&&object instanceof ImageBitmap){return true;}if(typeof OffscreenCanvas!=='undefined'&&object instanceof OffscreenCanvas){return true;}return false;}var NOOP=function NOOP(){};var WorkerThread=/*#__PURE__*/function(){function WorkerThread(props){_classCallCheck(this,WorkerThread);_defineProperty(this,"name",void 0);_defineProperty(this,"source",void 0);_defineProperty(this,"url",void 0);_defineProperty(this,"terminated",false);_defineProperty(this,"worker",void 0);_defineProperty(this,"onMessage",void 0);_defineProperty(this,"onError",void 0);_defineProperty(this,"_loadableURL",'');var name=props.name,source=props.source,url=props.url;assert$4(source||url);this.name=name;this.source=source;this.url=url;this.onMessage=NOOP;this.onError=function(error){return console.log(error);};this.worker=isBrowser$3?this._createBrowserWorker():this._createNodeWorker();}_createClass(WorkerThread,[{key:"destroy",value:function destroy(){this.onMessage=NOOP;this.onError=NOOP;this.worker.terminate();this.terminated=true;}},{key:"isRunning",get:function get(){return Boolean(this.onMessage);}},{key:"postMessage",value:function postMessage(data,transferList){transferList=transferList||getTransferList(data);this.worker.postMessage(data,transferList);}},{key:"_getErrorFromErrorEvent",value:function _getErrorFromErrorEvent(event){var message='Failed to load ';message+="worker ".concat(this.name," from ").concat(this.url,". ");if(event.message){message+="".concat(event.message," in ");}if(event.lineno){message+=":".concat(event.lineno,":").concat(event.colno);}return new Error(message);}},{key:"_createBrowserWorker",value:function _createBrowserWorker(){var _this113=this;this._loadableURL=getLoadableWorkerURL({source:this.source,url:this.url});var worker=new Worker(this._loadableURL,{name:this.name});worker.onmessage=function(event){if(!event.data){_this113.onError(new Error('No data received'));}else{_this113.onMessage(event.data);}};worker.onerror=function(error){_this113.onError(_this113._getErrorFromErrorEvent(error));_this113.terminated=true;};worker.onmessageerror=function(event){return console.error(event);};return worker;}},{key:"_createNodeWorker",value:function _createNodeWorker(){var _this114=this;var worker;if(this.url){var absolute=this.url.includes(':/')||this.url.startsWith('/');var url=absolute?this.url:"./".concat(this.url);worker=new Worker$1(url,{eval:false});}else if(this.source){worker=new Worker$1(this.source,{eval:true});}else{throw new Error('no worker');}worker.on('message',function(data){_this114.onMessage(data);});worker.on('error',function(error){_this114.onError(error);});worker.on('exit',function(code){});return worker;}}],[{key:"isSupported",value:function isSupported(){return typeof Worker!=='undefined'&&isBrowser$3||_typeof(Worker$1)!==undefined;}}]);return WorkerThread;}();var WorkerPool=/*#__PURE__*/function(){function WorkerPool(props){_classCallCheck(this,WorkerPool);_defineProperty(this,"name",'unnamed');_defineProperty(this,"source",void 0);_defineProperty(this,"url",void 0);_defineProperty(this,"maxConcurrency",1);_defineProperty(this,"maxMobileConcurrency",1);_defineProperty(this,"onDebug",function(){});_defineProperty(this,"reuseWorkers",true);_defineProperty(this,"props",{});_defineProperty(this,"jobQueue",[]);_defineProperty(this,"idleQueue",[]);_defineProperty(this,"count",0);_defineProperty(this,"isDestroyed",false);this.source=props.source;this.url=props.url;this.setProps(props);}_createClass(WorkerPool,[{key:"destroy",value:function destroy(){this.idleQueue.forEach(function(worker){return worker.destroy();});this.isDestroyed=true;}},{key:"setProps",value:function setProps(props){this.props=_objectSpread(_objectSpread({},this.props),props);if(props.name!==undefined){this.name=props.name;}if(props.maxConcurrency!==undefined){this.maxConcurrency=props.maxConcurrency;}if(props.maxMobileConcurrency!==undefined){this.maxMobileConcurrency=props.maxMobileConcurrency;}if(props.reuseWorkers!==undefined){this.reuseWorkers=props.reuseWorkers;}if(props.onDebug!==undefined){this.onDebug=props.onDebug;}}},{key:"startJob",value:function(){var _startJob=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name){var _this115=this;var onMessage,onError,startPromise,_args2=arguments;return _regeneratorRuntime().wrap(function _callee2$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:onMessage=_args2.length>1&&_args2[1]!==undefined?_args2[1]:function(job,type,data){return job.done(data);};onError=_args2.length>2&&_args2[2]!==undefined?_args2[2]:function(job,error){return job.error(error);};startPromise=new Promise(function(onStart){_this115.jobQueue.push({name:name,onMessage:onMessage,onError:onError,onStart:onStart});return _this115;});this._startQueuedJob();_context3.next=6;return startPromise;case 6:return _context3.abrupt("return",_context3.sent);case 7:case"end":return _context3.stop();}}},_callee2,this);}));function startJob(_x7){return _startJob.apply(this,arguments);}return startJob;}()},{key:"_startQueuedJob",value:function(){var _startQueuedJob2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(){var workerThread,queuedJob,job;return _regeneratorRuntime().wrap(function _callee3$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:if(this.jobQueue.length){_context4.next=2;break;}return _context4.abrupt("return");case 2:workerThread=this._getAvailableWorker();if(workerThread){_context4.next=5;break;}return _context4.abrupt("return");case 5:queuedJob=this.jobQueue.shift();if(!queuedJob){_context4.next=18;break;}this.onDebug({message:'Starting job',name:queuedJob.name,workerThread:workerThread,backlog:this.jobQueue.length});job=new WorkerJob(queuedJob.name,workerThread);workerThread.onMessage=function(data){return queuedJob.onMessage(job,data.type,data.payload);};workerThread.onError=function(error){return queuedJob.onError(job,error);};queuedJob.onStart(job);_context4.prev=12;_context4.next=15;return job.result;case 15:_context4.prev=15;this.returnWorkerToQueue(workerThread);return _context4.finish(15);case 18:case"end":return _context4.stop();}}},_callee3,this,[[12,,15,18]]);}));function _startQueuedJob(){return _startQueuedJob2.apply(this,arguments);}return _startQueuedJob;}()},{key:"returnWorkerToQueue",value:function returnWorkerToQueue(worker){var shouldDestroyWorker=this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency();if(shouldDestroyWorker){worker.destroy();this.count--;}else{this.idleQueue.push(worker);}if(!this.isDestroyed){this._startQueuedJob();}}},{key:"_getAvailableWorker",value:function _getAvailableWorker(){if(this.idleQueue.length>0){return this.idleQueue.shift()||null;}if(this.count0&&arguments[0]!==undefined?arguments[0]:{};WorkerFarm._workerFarm=WorkerFarm._workerFarm||new WorkerFarm({});WorkerFarm._workerFarm.setProps(props);return WorkerFarm._workerFarm;}}]);return WorkerFarm;}();_defineProperty(WorkerFarm,"_workerFarm",void 0);var NPM_TAG='latest';function getWorkerURL(worker){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var workerOptions=options[worker.id]||{};var workerFile="".concat(worker.id,"-worker.js");var url=workerOptions.workerUrl;if(!url&&worker.id==='compression'){url=options.workerUrl;}if(options._workerType==='test'){url="modules/".concat(worker.module,"/dist/").concat(workerFile);}if(!url){var version=worker.version;if(version==='latest'){version=NPM_TAG;}var versionTag=version?"@".concat(version):'';url="https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag,"/dist/").concat(workerFile);}assert$4(url);return url;}function validateWorkerVersion(worker){var coreVersion=arguments.length>1&&arguments[1]!==undefined?arguments[1]:VERSION$9;assert$4(worker,'no worker provided');var workerVersion=worker.version;if(!coreVersion||!workerVersion){return false;}return true;}var ChildProcessProxy={};var node=/*#__PURE__*/Object.freeze({__proto__:null,'default':ChildProcessProxy});var VERSION$8="3.2.6";var loadLibraryPromises={};function loadLibrary(_x8){return _loadLibrary.apply(this,arguments);}function _loadLibrary(){_loadLibrary=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(libraryUrl){var moduleName,options,_args4=arguments;return _regeneratorRuntime().wrap(function _callee7$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:moduleName=_args4.length>1&&_args4[1]!==undefined?_args4[1]:null;options=_args4.length>2&&_args4[2]!==undefined?_args4[2]:{};if(moduleName){libraryUrl=getLibraryUrl(libraryUrl,moduleName,options);}loadLibraryPromises[libraryUrl]=loadLibraryPromises[libraryUrl]||loadLibraryFromFile(libraryUrl);_context11.next=6;return loadLibraryPromises[libraryUrl];case 6:return _context11.abrupt("return",_context11.sent);case 7:case"end":return _context11.stop();}}},_callee7);}));return _loadLibrary.apply(this,arguments);}function getLibraryUrl(library,moduleName,options){if(library.startsWith('http')){return library;}var modules=options.modules||{};if(modules[library]){return modules[library];}if(!isBrowser$3){return"modules/".concat(moduleName,"/dist/libs/").concat(library);}if(options.CDN){assert$4(options.CDN.startsWith('http'));return"".concat(options.CDN,"/").concat(moduleName,"@").concat(VERSION$8,"/dist/libs/").concat(library);}if(isWorker){return"../src/libs/".concat(library);}return"modules/".concat(moduleName,"/src/libs/").concat(library);}function loadLibraryFromFile(_x9){return _loadLibraryFromFile.apply(this,arguments);}function _loadLibraryFromFile(){_loadLibraryFromFile=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(libraryUrl){var _response,response,scriptSource;return _regeneratorRuntime().wrap(function _callee8$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:if(!libraryUrl.endsWith('wasm')){_context12.next=7;break;}_context12.next=3;return fetch(libraryUrl);case 3:_response=_context12.sent;_context12.next=6;return _response.arrayBuffer();case 6:return _context12.abrupt("return",_context12.sent);case 7:if(isBrowser$3){_context12.next=20;break;}_context12.prev=8;_context12.t0=node&&undefined;if(!_context12.t0){_context12.next=14;break;}_context12.next=13;return undefined(libraryUrl);case 13:_context12.t0=_context12.sent;case 14:return _context12.abrupt("return",_context12.t0);case 17:_context12.prev=17;_context12.t1=_context12["catch"](8);return _context12.abrupt("return",null);case 20:if(!isWorker){_context12.next=22;break;}return _context12.abrupt("return",importScripts(libraryUrl));case 22:_context12.next=24;return fetch(libraryUrl);case 24:response=_context12.sent;_context12.next=27;return response.text();case 27:scriptSource=_context12.sent;return _context12.abrupt("return",loadLibraryFromString(scriptSource,libraryUrl));case 29:case"end":return _context12.stop();}}},_callee8,null,[[8,17]]);}));return _loadLibraryFromFile.apply(this,arguments);}function loadLibraryFromString(scriptSource,id){if(!isBrowser$3){return undefined&&undefined(scriptSource,id);}if(isWorker){eval.call(global_,scriptSource);return null;}var script=document.createElement('script');script.id=id;try{script.appendChild(document.createTextNode(scriptSource));}catch(e){script.text=scriptSource;}document.body.appendChild(script);return null;}function canParseWithWorker(loader,options){if(!WorkerFarm.isSupported()){return false;}if(!isBrowser$3&&!(options!==null&&options!==void 0&&options._nodeWorkers)){return false;}return loader.worker&&(options===null||options===void 0?void 0:options.worker);}function parseWithWorker(_x10,_x11,_x12,_x13,_x14){return _parseWithWorker.apply(this,arguments);}function _parseWithWorker(){_parseWithWorker=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(loader,data,options,context,parseOnMainThread){var name,url,workerFarm,workerPool,job,result;return _regeneratorRuntime().wrap(function _callee9$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:name=loader.id;url=getWorkerURL(loader,options);workerFarm=WorkerFarm.getWorkerFarm(options);workerPool=workerFarm.getWorkerPool({name:name,url:url});options=JSON.parse(JSON.stringify(options));context=JSON.parse(JSON.stringify(context||{}));_context13.next=8;return workerPool.startJob('process-on-worker',onMessage.bind(null,parseOnMainThread));case 8:job=_context13.sent;job.postMessage('process',{input:data,options:options,context:context});_context13.next=12;return job.result;case 12:result=_context13.sent;_context13.next=15;return result.result;case 15:return _context13.abrupt("return",_context13.sent);case 16:case"end":return _context13.stop();}}},_callee9);}));return _parseWithWorker.apply(this,arguments);}function onMessage(_x15,_x16,_x17,_x18){return _onMessage2.apply(this,arguments);}function _onMessage2(){_onMessage2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(parseOnMainThread,job,type,payload){var id,input,options,result,message;return _regeneratorRuntime().wrap(function _callee10$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:_context14.t0=type;_context14.next=_context14.t0==='done'?3:_context14.t0==='error'?5:_context14.t0==='process'?7:20;break;case 3:job.done(payload);return _context14.abrupt("break",21);case 5:job.error(new Error(payload.error));return _context14.abrupt("break",21);case 7:id=payload.id,input=payload.input,options=payload.options;_context14.prev=8;_context14.next=11;return parseOnMainThread(input,options);case 11:result=_context14.sent;job.postMessage('done',{id:id,result:result});_context14.next=19;break;case 15:_context14.prev=15;_context14.t1=_context14["catch"](8);message=_context14.t1 instanceof Error?_context14.t1.message:'unknown error';job.postMessage('error',{id:id,error:message});case 19:return _context14.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(type));case 21:case"end":return _context14.stop();}}},_callee10,null,[[8,15]]);}));return _onMessage2.apply(this,arguments);}function getFirstCharacters$1(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$2(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$2(data,byteOffset,length);}return'';}function getMagicString$2(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength<=byteOffset+length){return'';}var dataView=new DataView(arrayBuffer);var magic='';for(var _i494=0;_i494=0);assert$5(padding>0);return byteLength+(padding-1)&~(padding-1);}function copyToArray(source,target,targetOffset){var sourceArray;if(source instanceof ArrayBuffer){sourceArray=new Uint8Array(source);}else{var srcByteOffset=source.byteOffset;var srcByteLength=source.byteLength;sourceArray=new Uint8Array(source.buffer||source.arrayBuffer,srcByteOffset,srcByteLength);}target.set(sourceArray,targetOffset);return targetOffset+padToNBytes(sourceArray.byteLength,4);}function concatenateArrayBuffersAsync(_x19){return _concatenateArrayBuffersAsync.apply(this,arguments);}function _concatenateArrayBuffersAsync(){_concatenateArrayBuffersAsync=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(asyncIterator){var arrayBuffers,_iteratorAbruptCompletion,_didIteratorError,_iteratorError,_iterator,_step,chunk;return _regeneratorRuntime().wrap(function _callee11$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:arrayBuffers=[];_iteratorAbruptCompletion=false;_didIteratorError=false;_context15.prev=3;_iterator=_asyncIterator(asyncIterator);case 5:_context15.next=7;return _iterator.next();case 7:if(!(_iteratorAbruptCompletion=!(_step=_context15.sent).done)){_context15.next=13;break;}chunk=_step.value;arrayBuffers.push(chunk);case 10:_iteratorAbruptCompletion=false;_context15.next=5;break;case 13:_context15.next=19;break;case 15:_context15.prev=15;_context15.t0=_context15["catch"](3);_didIteratorError=true;_iteratorError=_context15.t0;case 19:_context15.prev=19;_context15.prev=20;if(!(_iteratorAbruptCompletion&&_iterator["return"]!=null)){_context15.next=24;break;}_context15.next=24;return _iterator["return"]();case 24:_context15.prev=24;if(!_didIteratorError){_context15.next=27;break;}throw _iteratorError;case 27:return _context15.finish(24);case 28:return _context15.finish(19);case 29:return _context15.abrupt("return",concatenateArrayBuffers.apply(void 0,arrayBuffers));case 30:case"end":return _context15.stop();}}},_callee11,null,[[3,15,19,29],[20,,24,28]]);}));return _concatenateArrayBuffersAsync.apply(this,arguments);}var pathPrefix='';var fileAliases={};function resolvePath(filename){for(var alias in fileAliases){if(filename.startsWith(alias)){var replacement=fileAliases[alias];filename=filename.replace(alias,replacement);}}if(!filename.startsWith('http://')&&!filename.startsWith('https://')){filename="".concat(pathPrefix).concat(filename);}return filename;}function filename(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(slashIndex+1):'';}var isBoolean=function isBoolean(x){return typeof x==='boolean';};var isFunction=function isFunction(x){return typeof x==='function';};var isObject=function isObject(x){return x!==null&&_typeof(x)==='object';};var isPureObject=function isPureObject(x){return isObject(x)&&x.constructor==={}.constructor;};var isIterable=function isIterable(x){return x&&typeof x[Symbol.iterator]==='function';};var isAsyncIterable=function isAsyncIterable(x){return x&&typeof x[Symbol.asyncIterator]==='function';};var isResponse=function isResponse(x){return typeof Response!=='undefined'&&x instanceof Response||x&&x.arrayBuffer&&x.text&&x.json;};var isBlob=function isBlob(x){return typeof Blob!=='undefined'&&x instanceof Blob;};var isBuffer=function isBuffer(x){return x&&_typeof(x)==='object'&&x.isBuffer;};var isReadableDOMStream=function isReadableDOMStream(x){return typeof ReadableStream!=='undefined'&&x instanceof ReadableStream||isObject(x)&&isFunction(x.tee)&&isFunction(x.cancel)&&isFunction(x.getReader);};var isReadableNodeStream=function isReadableNodeStream(x){return isObject(x)&&isFunction(x.read)&&isFunction(x.pipe)&&isBoolean(x.readable);};var isReadableStream=function isReadableStream(x){return isReadableDOMStream(x)||isReadableNodeStream(x);};var DATA_URL_PATTERN=/^data:([-\w.]+\/[-\w.+]+)(;|,)/;var MIME_TYPE_PATTERN=/^([-\w.]+\/[-\w.+]+)/;function parseMIMEType(mimeString){var matches=MIME_TYPE_PATTERN.exec(mimeString);if(matches){return matches[1];}return mimeString;}function parseMIMETypeFromURL(url){var matches=DATA_URL_PATTERN.exec(url);if(matches){return matches[1];}return'';}var QUERY_STRING_PATTERN=/\?.*/;function getResourceUrlAndType(resource){if(isResponse(resource)){var url=stripQueryString(resource.url||'');var contentTypeHeader=resource.headers.get('content-type')||'';return{url:url,type:parseMIMEType(contentTypeHeader)||parseMIMETypeFromURL(url)};}if(isBlob(resource)){return{url:stripQueryString(resource.name||''),type:resource.type||''};}if(typeof resource==='string'){return{url:stripQueryString(resource),type:parseMIMETypeFromURL(resource)};}return{url:'',type:''};}function getResourceContentLength(resource){if(isResponse(resource)){return resource.headers['content-length']||-1;}if(isBlob(resource)){return resource.size;}if(typeof resource==='string'){return resource.length;}if(resource instanceof ArrayBuffer){return resource.byteLength;}if(ArrayBuffer.isView(resource)){return resource.byteLength;}return-1;}function stripQueryString(url){return url.replace(QUERY_STRING_PATTERN,'');}function makeResponse(_x20){return _makeResponse.apply(this,arguments);}function _makeResponse(){_makeResponse=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(resource){var headers,contentLength,_getResourceUrlAndTyp3,url,type,initialDataUrl,response;return _regeneratorRuntime().wrap(function _callee12$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:if(!isResponse(resource)){_context16.next=2;break;}return _context16.abrupt("return",resource);case 2:headers={};contentLength=getResourceContentLength(resource);if(contentLength>=0){headers['content-length']=String(contentLength);}_getResourceUrlAndTyp3=getResourceUrlAndType(resource),url=_getResourceUrlAndTyp3.url,type=_getResourceUrlAndTyp3.type;if(type){headers['content-type']=type;}_context16.next=9;return getInitialDataUrl(resource);case 9:initialDataUrl=_context16.sent;if(initialDataUrl){headers['x-first-bytes']=initialDataUrl;}if(typeof resource==='string'){resource=new TextEncoder().encode(resource);}response=new Response(resource,{headers:headers});Object.defineProperty(response,'url',{value:url});return _context16.abrupt("return",response);case 15:case"end":return _context16.stop();}}},_callee12);}));return _makeResponse.apply(this,arguments);}function checkResponse(_x21){return _checkResponse.apply(this,arguments);}function _checkResponse(){_checkResponse=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(response){var message;return _regeneratorRuntime().wrap(function _callee13$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:if(response.ok){_context17.next=5;break;}_context17.next=3;return getResponseError(response);case 3:message=_context17.sent;throw new Error(message);case 5:case"end":return _context17.stop();}}},_callee13);}));return _checkResponse.apply(this,arguments);}function getResponseError(_x22){return _getResponseError.apply(this,arguments);}function _getResponseError(){_getResponseError=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(response){var message,contentType,text;return _regeneratorRuntime().wrap(function _callee14$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:message="Failed to fetch resource ".concat(response.url," (").concat(response.status,"): ");_context18.prev=1;contentType=response.headers.get('Content-Type');text=response.statusText;if(!contentType.includes('application/json')){_context18.next=11;break;}_context18.t0=text;_context18.t1=" ";_context18.next=9;return response.text();case 9:_context18.t2=_context18.sent;text=_context18.t0+=_context18.t1.concat.call(_context18.t1,_context18.t2);case 11:message+=text;message=message.length>60?"".concat(message.slice(0,60),"..."):message;_context18.next=17;break;case 15:_context18.prev=15;_context18.t3=_context18["catch"](1);case 17:return _context18.abrupt("return",message);case 18:case"end":return _context18.stop();}}},_callee14,null,[[1,15]]);}));return _getResponseError.apply(this,arguments);}function getInitialDataUrl(_x23){return _getInitialDataUrl.apply(this,arguments);}function _getInitialDataUrl(){_getInitialDataUrl=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15(resource){var INITIAL_DATA_LENGTH,blobSlice,slice,_base;return _regeneratorRuntime().wrap(function _callee15$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:INITIAL_DATA_LENGTH=5;if(!(typeof resource==='string')){_context19.next=3;break;}return _context19.abrupt("return","data:,".concat(resource.slice(0,INITIAL_DATA_LENGTH)));case 3:if(!(resource instanceof Blob)){_context19.next=8;break;}blobSlice=resource.slice(0,5);_context19.next=7;return new Promise(function(resolve){var reader=new FileReader();reader.onload=function(event){var _event$target;return resolve(event===null||event===void 0?void 0:(_event$target=event.target)===null||_event$target===void 0?void 0:_event$target.result);};reader.readAsDataURL(blobSlice);});case 7:return _context19.abrupt("return",_context19.sent);case 8:if(!(resource instanceof ArrayBuffer)){_context19.next=12;break;}slice=resource.slice(0,INITIAL_DATA_LENGTH);_base=arrayBufferToBase64(slice);return _context19.abrupt("return","data:base64,".concat(_base));case 12:return _context19.abrupt("return",null);case 13:case"end":return _context19.stop();}}},_callee15);}));return _getInitialDataUrl.apply(this,arguments);}function arrayBufferToBase64(buffer){var binary='';var bytes=new Uint8Array(buffer);for(var _i496=0;_i496=0){return true;}return false;}function isBrowser$2(){var isNode=(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&String(process)==='[object process]'&&!process.browser;return!isNode||isElectron$1();}var globals$1={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&process};var window_$1=globals$1.window||globals$1.self||globals$1.global;var process_$1=globals$1.process||{};var VERSION$7=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';var isBrowser$1=isBrowser$2();function getStorage$1(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}var LocalStorage$1=/*#__PURE__*/function(){function LocalStorage$1(id,defaultSettings){var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_classCallCheck(this,LocalStorage$1);this.storage=getStorage$1(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}_createClass(LocalStorage$1,[{key:"getConfiguration",value:function getConfiguration(){return this.config;}},{key:"setConfiguration",value:function setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}},{key:"updateConfiguration",value:function updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}},{key:"_loadConfiguration",value:function _loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}]);return LocalStorage$1;}();function formatTime$1(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else{formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad$1(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return"".concat(' '.repeat(padLength)).concat(string);}function formatImage$1(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return["".concat(message," %c+"),style];}var COLOR$1={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function getColor$1(color){return typeof color==='string'?COLOR$1[color.toUpperCase()]||COLOR$1.WHITE:color;}function addColor$1(string,color,background){if(!isBrowser$1&&typeof string==='string'){if(color){color=getColor$1(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor$1(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind$1(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _iterator7=_createForOfIteratorHelper(propNames),_step7;try{var _loop4=function _loop4(){var key=_step7.value;if(typeof obj[key]==='function'){if(!predefined.find(function(name){return key===name;})){obj[key]=obj[key].bind(obj);}}};for(_iterator7.s();!(_step7=_iterator7.n()).done;){_loop4();}}catch(err){_iterator7.e(err);}finally{_iterator7.f();}}function assert$3(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp$1(){var timestamp;if(isBrowser$1&&window_$1.performance){timestamp=window_$1.performance.now();}else if(process_$1.hrtime){var timeParts=process_$1.hrtime();timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else{timestamp=Date.now();}return timestamp;}var originalConsole$1={debug:isBrowser$1?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS$1={enabled:true,level:0};function noop$1(){}var cache$1={};var ONCE$1={once:true};function getTableHeader$1(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return'empty';}var Log$1=/*#__PURE__*/function(){function Log$1(){var _ref16=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''},id=_ref16.id;_classCallCheck(this,Log$1);this.id=id;this.VERSION=VERSION$7;this._startTs=getHiResTimestamp$1();this._deltaTs=getHiResTimestamp$1();this.LOG_THROTTLE_TIMEOUT=0;this._storage=new LocalStorage$1("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS$1);this.userData={};this.timeStamp("".concat(this.id," started"));autobind$1(this);Object.seal(this);}_createClass(Log$1,[{key:"level",get:function get(){return this.getLevel();},set:function set(newLevel){this.setLevel(newLevel);}},{key:"isEnabled",value:function isEnabled(){return this._storage.config.enabled;}},{key:"getLevel",value:function getLevel(){return this._storage.config.level;}},{key:"getTotal",value:function getTotal(){return Number((getHiResTimestamp$1()-this._startTs).toPrecision(10));}},{key:"getDelta",value:function getDelta(){return Number((getHiResTimestamp$1()-this._deltaTs).toPrecision(10));}},{key:"priority",get:function get(){return this.level;},set:function set(newPriority){this.level=newPriority;}},{key:"getPriority",value:function getPriority(){return this.level;}},{key:"enable",value:function enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled:enabled});return this;}},{key:"setLevel",value:function setLevel(level){this._storage.updateConfiguration({level:level});return this;}},{key:"assert",value:function assert(condition,message){assert$3(condition,message);}},{key:"warn",value:function warn(message){return this._getLogFunction(0,message,originalConsole$1.warn,arguments,ONCE$1);}},{key:"error",value:function error(message){return this._getLogFunction(0,message,originalConsole$1.error,arguments);}},{key:"deprecated",value:function deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}},{key:"removed",value:function removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}},{key:"probe",value:function probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.log,arguments,{time:true,once:true});}},{key:"log",value:function log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.debug,arguments);}},{key:"info",value:function info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}},{key:"once",value:function once(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.debug||originalConsole$1.info,arguments,ONCE$1);}},{key:"table",value:function table(logLevel,_table,columns){if(_table){return this._getLogFunction(logLevel,_table,console.table||noop$1,columns&&[columns],{tag:getTableHeader$1(_table)});}return noop$1;}},{key:"image",value:function(_image6){function image(_x26){return _image6.apply(this,arguments);}image.toString=function(){return _image6.toString();};return image;}(function(_ref17){var logLevel=_ref17.logLevel,priority=_ref17.priority,image=_ref17.image,_ref17$message=_ref17.message,message=_ref17$message===void 0?'':_ref17$message,_ref17$scale=_ref17.scale,scale=_ref17$scale===void 0?1:_ref17$scale;if(!this._shouldLog(logLevel||priority)){return noop$1;}return isBrowser$1?logImageInBrowser$1({image:image,message:message,scale:scale}):logImageInNode$1({image:image,message:message,scale:scale});})},{key:"settings",value:function settings(){if(console.table){console.table(this._storage.config);}else{console.log(this._storage.config);}}},{key:"get",value:function get(setting){return this._storage.config[setting];}},{key:"set",value:function set(setting,value){this._storage.updateConfiguration(_defineProperty2({},setting,value));}},{key:"time",value:function time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}},{key:"timeEnd",value:function timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}},{key:"timeStamp",value:function timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop$1);}},{key:"group",value:function group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};opts=normalizeArguments$1({logLevel:logLevel,message:message,opts:opts});var _opts=opts,collapsed=_opts.collapsed;opts.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(opts);}},{key:"groupCollapsed",value:function groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}},{key:"groupEnd",value:function groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop$1);}},{key:"withGroup",value:function withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}},{key:"trace",value:function trace(){if(console.trace){console.trace();}}},{key:"_shouldLog",value:function _shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel$1(logLevel);}},{key:"_getLogFunction",value:function _getLogFunction(logLevel,message,method){var args=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[];var opts=arguments.length>4?arguments[4]:undefined;if(this._shouldLog(logLevel)){var _method;opts=normalizeArguments$1({logLevel:logLevel,message:message,args:args,opts:opts});method=method||opts.method;assert$3(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp$1();var tag=opts.tag||opts.message;if(opts.once){if(!cache$1[tag]){cache$1[tag]=getHiResTimestamp$1();}else{return noop$1;}}message=decorateMessage$1(this.id,opts.message,opts);return(_method=method).bind.apply(_method,[console,message].concat(_toConsumableArray(opts.args)));}return noop$1;}}]);return Log$1;}();Log$1.VERSION=VERSION$7;function normalizeLogLevel$1(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(_typeof(logLevel)){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$3(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments$1(opts){var logLevel=opts.logLevel,message=opts.message;opts.logLevel=normalizeLogLevel$1(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}opts.args=args;switch(_typeof(logLevel)){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=_typeof(opts.message);assert$3(messageType==='string'||messageType==='object');return Object.assign(opts,opts.opts);}function decorateMessage$1(id,message,opts){if(typeof message==='string'){var _time=opts.time?leftPad$1(formatTime$1(opts.total)):'';message=opts.time?"".concat(id,": ").concat(_time," ").concat(message):"".concat(id,": ").concat(message);message=addColor$1(message,opts.color,opts.background);}return message;}function logImageInNode$1(_ref18){var image=_ref18.image,_ref18$message=_ref18.message,message=_ref18$message===void 0?'':_ref18$message,_ref18$scale=_ref18.scale,scale=_ref18$scale===void 0?1:_ref18$scale;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return function(){return asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(function(data){return console.log(data);});};}return noop$1;}function logImageInBrowser$1(_ref19){var image=_ref19.image,_ref19$message=_ref19.message,message=_ref19$message===void 0?'':_ref19$message,_ref19$scale=_ref19.scale,scale=_ref19$scale===void 0?1:_ref19$scale;if(typeof image==='string'){var img=new Image();img.onload=function(){var _console;var args=formatImage$1(img,message,scale);(_console=console).log.apply(_console,_toConsumableArray(args));};img.src=image;return noop$1;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){var _console2;(_console2=console).log.apply(_console2,_toConsumableArray(formatImage$1(image,message,scale)));return noop$1;}if(element.toLowerCase()==='canvas'){var _img=new Image();_img.onload=function(){var _console3;return(_console3=console).log.apply(_console3,_toConsumableArray(formatImage$1(_img,message,scale)));};_img.src=image.toDataURL();return noop$1;}return noop$1;}var probeLog=new Log$1({id:'loaders.gl'});var NullLog=/*#__PURE__*/function(){function NullLog(){_classCallCheck(this,NullLog);}_createClass(NullLog,[{key:"log",value:function log(){return function(){};}},{key:"info",value:function info(){return function(){};}},{key:"warn",value:function warn(){return function(){};}},{key:"error",value:function error(){return function(){};}}]);return NullLog;}();var ConsoleLog=/*#__PURE__*/function(){function ConsoleLog(){_classCallCheck(this,ConsoleLog);_defineProperty(this,"console",void 0);this.console=console;}_createClass(ConsoleLog,[{key:"log",value:function log(){var _this$console$log;for(var _len103=arguments.length,args=new Array(_len103),_key7=0;_key7<_len103;_key7++){args[_key7]=arguments[_key7];}return(_this$console$log=this.console.log).bind.apply(_this$console$log,[this.console].concat(args));}},{key:"info",value:function info(){var _this$console$info;for(var _len104=arguments.length,args=new Array(_len104),_key8=0;_key8<_len104;_key8++){args[_key8]=arguments[_key8];}return(_this$console$info=this.console.info).bind.apply(_this$console$info,[this.console].concat(args));}},{key:"warn",value:function warn(){var _this$console$warn;for(var _len105=arguments.length,args=new Array(_len105),_key9=0;_key9<_len105;_key9++){args[_key9]=arguments[_key9];}return(_this$console$warn=this.console.warn).bind.apply(_this$console$warn,[this.console].concat(args));}},{key:"error",value:function error(){var _this$console$error;for(var _len106=arguments.length,args=new Array(_len106),_key10=0;_key10<_len106;_key10++){args[_key10]=arguments[_key10];}return(_this$console$error=this.console.error).bind.apply(_this$console$error,[this.console].concat(args));}}]);return ConsoleLog;}();var DEFAULT_LOADER_OPTIONS={fetch:null,mimeType:undefined,nothrow:false,log:new ConsoleLog(),CDN:'https://unpkg.com/@loaders.gl',worker:true,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:isBrowser$4,_nodeWorkers:false,_workerType:'',limit:0,_limitMB:0,batchSize:'auto',batchDebounceMs:0,metadata:false,transforms:[]};var REMOVED_LOADER_OPTIONS={"throws":'nothrow',dataType:'(no longer used)',uri:'baseUri',method:'fetch.method',headers:'fetch.headers',body:'fetch.body',mode:'fetch.mode',credentials:'fetch.credentials',cache:'fetch.cache',redirect:'fetch.redirect',referrer:'fetch.referrer',referrerPolicy:'fetch.referrerPolicy',integrity:'fetch.integrity',keepalive:'fetch.keepalive',signal:'fetch.signal'};function getGlobalLoaderState(){globalThis.loaders=globalThis.loaders||{};var loaders=globalThis.loaders;loaders._state=loaders._state||{};return loaders._state;}var getGlobalLoaderOptions=function getGlobalLoaderOptions(){var state=getGlobalLoaderState();state.globalOptions=state.globalOptions||_objectSpread({},DEFAULT_LOADER_OPTIONS);return state.globalOptions;};function normalizeOptions(options,loader,loaders,url){loaders=loaders||[];loaders=Array.isArray(loaders)?loaders:[loaders];validateOptions(options,loaders);return normalizeOptionsInternal(loader,options,url);}function getFetchFunction(options,context){var globalOptions=getGlobalLoaderOptions();var fetchOptions=options||globalOptions;if(typeof fetchOptions.fetch==='function'){return fetchOptions.fetch;}if(isObject(fetchOptions.fetch)){return function(url){return fetchFile(url,fetchOptions);};}if(context!==null&&context!==void 0&&context.fetch){return context===null||context===void 0?void 0:context.fetch;}return fetchFile;}function validateOptions(options,loaders){validateOptionsObject(options,null,DEFAULT_LOADER_OPTIONS,REMOVED_LOADER_OPTIONS,loaders);var _iterator8=_createForOfIteratorHelper(loaders),_step8;try{for(_iterator8.s();!(_step8=_iterator8.n()).done;){var loader=_step8.value;var idOptions=options&&options[loader.id]||{};var loaderOptions=loader.options&&loader.options[loader.id]||{};var deprecatedOptions=loader.deprecatedOptions&&loader.deprecatedOptions[loader.id]||{};validateOptionsObject(idOptions,loader.id,loaderOptions,deprecatedOptions,loaders);}}catch(err){_iterator8.e(err);}finally{_iterator8.f();}}function validateOptionsObject(options,id,defaultOptions,deprecatedOptions,loaders){var loaderName=id||'Top level';var prefix=id?"".concat(id,"."):'';for(var key in options){var isSubOptions=!id&&isObject(options[key]);var isBaseUriOption=key==='baseUri'&&!id;var isWorkerUrlOption=key==='workerUrl'&&id;if(!(key in defaultOptions)&&!isBaseUriOption&&!isWorkerUrlOption){if(key in deprecatedOptions){probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' no longer supported, use '").concat(deprecatedOptions[key],"'"))();}else if(!isSubOptions){var suggestion=findSimilarOption(key,loaders);probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' not recognized. ").concat(suggestion))();}}}}function findSimilarOption(optionKey,loaders){var lowerCaseOptionKey=optionKey.toLowerCase();var bestSuggestion='';var _iterator9=_createForOfIteratorHelper(loaders),_step9;try{for(_iterator9.s();!(_step9=_iterator9.n()).done;){var loader=_step9.value;for(var key in loader.options){if(optionKey===key){return"Did you mean '".concat(loader.id,".").concat(key,"'?");}var lowerCaseKey=key.toLowerCase();var isPartialMatch=lowerCaseOptionKey.startsWith(lowerCaseKey)||lowerCaseKey.startsWith(lowerCaseOptionKey);if(isPartialMatch){bestSuggestion=bestSuggestion||"Did you mean '".concat(loader.id,".").concat(key,"'?");}}}}catch(err){_iterator9.e(err);}finally{_iterator9.f();}return bestSuggestion;}function normalizeOptionsInternal(loader,options,url){var loaderDefaultOptions=loader.options||{};var mergedOptions=_objectSpread({},loaderDefaultOptions);addUrlOptions(mergedOptions,url);if(mergedOptions.log===null){mergedOptions.log=new NullLog();}mergeNestedFields(mergedOptions,getGlobalLoaderOptions());mergeNestedFields(mergedOptions,options);return mergedOptions;}function mergeNestedFields(mergedOptions,options){for(var key in options){if(key in options){var value=options[key];if(isPureObject(value)&&isPureObject(mergedOptions[key])){mergedOptions[key]=_objectSpread(_objectSpread({},mergedOptions[key]),options[key]);}else{mergedOptions[key]=options[key];}}}}function addUrlOptions(options,url){if(url&&!('baseUri'in options)){options.baseUri=url;}}function isLoaderObject(loader){var _loader;if(!loader){return false;}if(Array.isArray(loader)){loader=loader[0];}var hasExtensions=Array.isArray((_loader=loader)===null||_loader===void 0?void 0:_loader.extensions);return hasExtensions;}function normalizeLoader(loader){var _loader2,_loader3;assert$5(loader,'null loader');assert$5(isLoaderObject(loader),'invalid loader');var options;if(Array.isArray(loader)){options=loader[1];loader=loader[0];loader=_objectSpread(_objectSpread({},loader),{},{options:_objectSpread(_objectSpread({},loader.options),options)});}if((_loader2=loader)!==null&&_loader2!==void 0&&_loader2.parseTextSync||(_loader3=loader)!==null&&_loader3!==void 0&&_loader3.parseText){loader.text=true;}if(!loader.text){loader.binary=true;}return loader;}var getGlobalLoaderRegistry=function getGlobalLoaderRegistry(){var state=getGlobalLoaderState();state.loaderRegistry=state.loaderRegistry||[];return state.loaderRegistry;};function getRegisteredLoaders(){return getGlobalLoaderRegistry();}function isElectron(mockUserAgent){if(typeof window!=='undefined'&&_typeof(window.process)==='object'&&window.process.type==='renderer'){return true;}if(typeof process!=='undefined'&&_typeof(process.versions)==='object'&&Boolean(process.versions.electron)){return true;}var realUserAgent=(typeof navigator==="undefined"?"undefined":_typeof(navigator))==='object'&&typeof navigator.userAgent==='string'&&navigator.userAgent;var userAgent=mockUserAgent||realUserAgent;if(userAgent&&userAgent.indexOf('Electron')>=0){return true;}return false;}function isBrowser(){var isNode=(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&String(process)==='[object process]'&&!process.browser;return!isNode||isElectron();}var globals={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&process};var window_=globals.window||globals.self||globals.global;var process_=globals.process||{};var VERSION$6=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';isBrowser();function getStorage(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}var LocalStorage=/*#__PURE__*/function(){function LocalStorage(id){_classCallCheck(this,LocalStorage);var defaultSettings=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_defineProperty(this,"storage",void 0);_defineProperty(this,"id",void 0);_defineProperty(this,"config",{});this.storage=getStorage(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}_createClass(LocalStorage,[{key:"getConfiguration",value:function getConfiguration(){return this.config;}},{key:"setConfiguration",value:function setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}},{key:"updateConfiguration",value:function updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}},{key:"_loadConfiguration",value:function _loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}]);return LocalStorage;}();function formatTime(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else{formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return"".concat(' '.repeat(padLength)).concat(string);}function formatImage(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return["".concat(message," %c+"),style];}var COLOR;(function(COLOR){COLOR[COLOR["BLACK"]=30]="BLACK";COLOR[COLOR["RED"]=31]="RED";COLOR[COLOR["GREEN"]=32]="GREEN";COLOR[COLOR["YELLOW"]=33]="YELLOW";COLOR[COLOR["BLUE"]=34]="BLUE";COLOR[COLOR["MAGENTA"]=35]="MAGENTA";COLOR[COLOR["CYAN"]=36]="CYAN";COLOR[COLOR["WHITE"]=37]="WHITE";COLOR[COLOR["BRIGHT_BLACK"]=90]="BRIGHT_BLACK";COLOR[COLOR["BRIGHT_RED"]=91]="BRIGHT_RED";COLOR[COLOR["BRIGHT_GREEN"]=92]="BRIGHT_GREEN";COLOR[COLOR["BRIGHT_YELLOW"]=93]="BRIGHT_YELLOW";COLOR[COLOR["BRIGHT_BLUE"]=94]="BRIGHT_BLUE";COLOR[COLOR["BRIGHT_MAGENTA"]=95]="BRIGHT_MAGENTA";COLOR[COLOR["BRIGHT_CYAN"]=96]="BRIGHT_CYAN";COLOR[COLOR["BRIGHT_WHITE"]=97]="BRIGHT_WHITE";})(COLOR||(COLOR={}));function getColor(color){return typeof color==='string'?COLOR[color.toUpperCase()]||COLOR.WHITE:color;}function addColor(string,color,background){if(!isBrowser&&typeof string==='string'){if(color){color=getColor(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _iterator10=_createForOfIteratorHelper(propNames),_step10;try{var _loop5=function _loop5(){var key=_step10.value;if(typeof obj[key]==='function'){if(!predefined.find(function(name){return key===name;})){obj[key]=obj[key].bind(obj);}}};for(_iterator10.s();!(_step10=_iterator10.n()).done;){_loop5();}}catch(err){_iterator10.e(err);}finally{_iterator10.f();}}function assert$2(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp(){var timestamp;if(isBrowser&&'performance'in window_){var _window$performance,_window$performance$n;timestamp=window_===null||window_===void 0?void 0:(_window$performance=window_.performance)===null||_window$performance===void 0?void 0:(_window$performance$n=_window$performance.now)===null||_window$performance$n===void 0?void 0:_window$performance$n.call(_window$performance);}else if('hrtime'in process_){var _process$hrtime;var timeParts=process_===null||process_===void 0?void 0:(_process$hrtime=process_.hrtime)===null||_process$hrtime===void 0?void 0:_process$hrtime.call(process_);timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else{timestamp=Date.now();}return timestamp;}var originalConsole={debug:isBrowser?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS={enabled:true,level:0};function noop(){}var cache={};var ONCE={once:true};var Log=/*#__PURE__*/function(){function Log(){_classCallCheck(this,Log);var _ref20=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''},id=_ref20.id;_defineProperty(this,"id",void 0);_defineProperty(this,"VERSION",VERSION$6);_defineProperty(this,"_startTs",getHiResTimestamp());_defineProperty(this,"_deltaTs",getHiResTimestamp());_defineProperty(this,"_storage",void 0);_defineProperty(this,"userData",{});_defineProperty(this,"LOG_THROTTLE_TIMEOUT",0);this.id=id;this._storage=new LocalStorage("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS);this.userData={};this.timeStamp("".concat(this.id," started"));autobind(this);Object.seal(this);}_createClass(Log,[{key:"level",get:function get(){return this.getLevel();},set:function set(newLevel){this.setLevel(newLevel);}},{key:"isEnabled",value:function isEnabled(){return this._storage.config.enabled;}},{key:"getLevel",value:function getLevel(){return this._storage.config.level;}},{key:"getTotal",value:function getTotal(){return Number((getHiResTimestamp()-this._startTs).toPrecision(10));}},{key:"getDelta",value:function getDelta(){return Number((getHiResTimestamp()-this._deltaTs).toPrecision(10));}},{key:"priority",get:function get(){return this.level;},set:function set(newPriority){this.level=newPriority;}},{key:"getPriority",value:function getPriority(){return this.level;}},{key:"enable",value:function enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled:enabled});return this;}},{key:"setLevel",value:function setLevel(level){this._storage.updateConfiguration({level:level});return this;}},{key:"get",value:function get(setting){return this._storage.config[setting];}},{key:"set",value:function set(setting,value){this._storage.updateConfiguration(_defineProperty2({},setting,value));}},{key:"settings",value:function settings(){if(console.table){console.table(this._storage.config);}else{console.log(this._storage.config);}}},{key:"assert",value:function assert(condition,message){assert$2(condition,message);}},{key:"warn",value:function warn(message){return this._getLogFunction(0,message,originalConsole.warn,arguments,ONCE);}},{key:"error",value:function error(message){return this._getLogFunction(0,message,originalConsole.error,arguments);}},{key:"deprecated",value:function deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}},{key:"removed",value:function removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}},{key:"probe",value:function probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.log,arguments,{time:true,once:true});}},{key:"log",value:function log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.debug,arguments);}},{key:"info",value:function info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}},{key:"once",value:function once(logLevel,message){for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}return this._getLogFunction(logLevel,message,originalConsole.debug||originalConsole.info,arguments,ONCE);}},{key:"table",value:function table(logLevel,_table2,columns){if(_table2){return this._getLogFunction(logLevel,_table2,console.table||noop,columns&&[columns],{tag:getTableHeader(_table2)});}return noop;}},{key:"image",value:function image(_ref){var logLevel=_ref.logLevel,priority=_ref.priority,image=_ref.image,_ref$message=_ref.message,message=_ref$message===void 0?'':_ref$message,_ref$scale=_ref.scale,scale=_ref$scale===void 0?1:_ref$scale;if(!this._shouldLog(logLevel||priority)){return noop;}return isBrowser?logImageInBrowser({image:image,message:message,scale:scale}):logImageInNode({image:image,message:message,scale:scale});}},{key:"time",value:function time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}},{key:"timeEnd",value:function timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}},{key:"timeStamp",value:function timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop);}},{key:"group",value:function group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};var options=normalizeArguments({logLevel:logLevel,message:message,opts:opts});var collapsed=opts.collapsed;options.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(options);}},{key:"groupCollapsed",value:function groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}},{key:"groupEnd",value:function groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop);}},{key:"withGroup",value:function withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}},{key:"trace",value:function trace(){if(console.trace){console.trace();}}},{key:"_shouldLog",value:function _shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel(logLevel);}},{key:"_getLogFunction",value:function _getLogFunction(logLevel,message,method,args,opts){if(this._shouldLog(logLevel)){var _method2;opts=normalizeArguments({logLevel:logLevel,message:message,args:args,opts:opts});method=method||opts.method;assert$2(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp();var tag=opts.tag||opts.message;if(opts.once){if(!cache[tag]){cache[tag]=getHiResTimestamp();}else{return noop;}}message=decorateMessage(this.id,opts.message,opts);return(_method2=method).bind.apply(_method2,[console,message].concat(_toConsumableArray(opts.args)));}return noop;}}]);return Log;}();_defineProperty(Log,"VERSION",VERSION$6);function normalizeLogLevel(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(_typeof(logLevel)){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$2(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments(opts){var logLevel=opts.logLevel,message=opts.message;opts.logLevel=normalizeLogLevel(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}switch(_typeof(logLevel)){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=_typeof(opts.message);assert$2(messageType==='string'||messageType==='object');return Object.assign(opts,{args:args},opts.opts);}function decorateMessage(id,message,opts){if(typeof message==='string'){var _time2=opts.time?leftPad(formatTime(opts.total)):'';message=opts.time?"".concat(id,": ").concat(_time2," ").concat(message):"".concat(id,": ").concat(message);message=addColor(message,opts.color,opts.background);}return message;}function logImageInNode(_ref2){var image=_ref2.image,_ref2$message=_ref2.message,message=_ref2$message===void 0?'':_ref2$message,_ref2$scale=_ref2.scale,scale=_ref2$scale===void 0?1:_ref2$scale;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return function(){return asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(function(data){return console.log(data);});};}return noop;}function logImageInBrowser(_ref3){var image=_ref3.image,_ref3$message=_ref3.message,message=_ref3$message===void 0?'':_ref3$message,_ref3$scale=_ref3.scale,scale=_ref3$scale===void 0?1:_ref3$scale;if(typeof image==='string'){var img=new Image();img.onload=function(){var _console4;var args=formatImage(img,message,scale);(_console4=console).log.apply(_console4,_toConsumableArray(args));};img.src=image;return noop;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){var _console5;(_console5=console).log.apply(_console5,_toConsumableArray(formatImage(image,message,scale)));return noop;}if(element.toLowerCase()==='canvas'){var _img2=new Image();_img2.onload=function(){var _console6;return(_console6=console).log.apply(_console6,_toConsumableArray(formatImage(_img2,message,scale)));};_img2.src=image.toDataURL();return noop;}return noop;}function getTableHeader(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return'empty';}var log=new Log({id:'loaders.gl'});var EXT_PATTERN=/\.([^.]+)$/;function selectLoader(_x27){return _selectLoader.apply(this,arguments);}function _selectLoader(){_selectLoader=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17(data){var loaders,options,context,loader,_args15=arguments;return _regeneratorRuntime().wrap(function _callee17$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:loaders=_args15.length>1&&_args15[1]!==undefined?_args15[1]:[];options=_args15.length>2?_args15[2]:undefined;context=_args15.length>3?_args15[3]:undefined;if(validHTTPResponse(data)){_context21.next=5;break;}return _context21.abrupt("return",null);case 5:loader=selectLoaderSync(data,loaders,_objectSpread(_objectSpread({},options),{},{nothrow:true}),context);if(!loader){_context21.next=8;break;}return _context21.abrupt("return",loader);case 8:if(!isBlob(data)){_context21.next=13;break;}_context21.next=11;return data.slice(0,10).arrayBuffer();case 11:data=_context21.sent;loader=selectLoaderSync(data,loaders,options,context);case 13:if(!(!loader&&!(options!==null&&options!==void 0&&options.nothrow))){_context21.next=15;break;}throw new Error(getNoValidLoaderMessage(data));case 15:return _context21.abrupt("return",loader);case 16:case"end":return _context21.stop();}}},_callee17);}));return _selectLoader.apply(this,arguments);}function selectLoaderSync(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}if(loaders&&!Array.isArray(loaders)){return normalizeLoader(loaders);}var candidateLoaders=[];if(loaders){candidateLoaders=candidateLoaders.concat(loaders);}if(!(options!==null&&options!==void 0&&options.ignoreRegisteredLoaders)){var _candidateLoaders;(_candidateLoaders=candidateLoaders).push.apply(_candidateLoaders,_toConsumableArray(getRegisteredLoaders()));}normalizeLoaders(candidateLoaders);var loader=selectLoaderInternal(data,candidateLoaders,options,context);if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;}function selectLoaderInternal(data,loaders,options,context){var _getResourceUrlAndTyp=getResourceUrlAndType(data),url=_getResourceUrlAndTyp.url,type=_getResourceUrlAndTyp.type;var testUrl=url||(context===null||context===void 0?void 0:context.url);var loader=null;var reason='';if(options!==null&&options!==void 0&&options.mimeType){loader=findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.mimeType);reason="match forced by supplied MIME type ".concat(options===null||options===void 0?void 0:options.mimeType);}loader=loader||findLoaderByUrl(loaders,testUrl);reason=reason||(loader?"matched url ".concat(testUrl):'');loader=loader||findLoaderByMIMEType(loaders,type);reason=reason||(loader?"matched MIME type ".concat(type):'');loader=loader||findLoaderByInitialBytes(loaders,data);reason=reason||(loader?"matched initial data ".concat(getFirstCharacters(data)):'');loader=loader||findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.fallbackMimeType);reason=reason||(loader?"matched fallback MIME type ".concat(type):'');if(reason){var _loader;log.log(1,"selectLoader selected ".concat((_loader=loader)===null||_loader===void 0?void 0:_loader.name,": ").concat(reason,"."));}return loader;}function validHTTPResponse(data){if(data instanceof Response){if(data.status===204){return false;}}return true;}function getNoValidLoaderMessage(data){var _getResourceUrlAndTyp2=getResourceUrlAndType(data),url=_getResourceUrlAndTyp2.url,type=_getResourceUrlAndTyp2.type;var message='No valid loader found (';message+=url?"".concat(filename(url),", "):'no url provided, ';message+="MIME type: ".concat(type?"\"".concat(type,"\""):'not provided',", ");var firstCharacters=data?getFirstCharacters(data):'';message+=firstCharacters?" first bytes: \"".concat(firstCharacters,"\""):'first bytes: not available';message+=')';return message;}function normalizeLoaders(loaders){var _iterator11=_createForOfIteratorHelper(loaders),_step11;try{for(_iterator11.s();!(_step11=_iterator11.n()).done;){var loader=_step11.value;normalizeLoader(loader);}}catch(err){_iterator11.e(err);}finally{_iterator11.f();}}function findLoaderByUrl(loaders,url){var match=url&&EXT_PATTERN.exec(url);var extension=match&&match[1];return extension?findLoaderByExtension(loaders,extension):null;}function findLoaderByExtension(loaders,extension){extension=extension.toLowerCase();var _iterator12=_createForOfIteratorHelper(loaders),_step12;try{for(_iterator12.s();!(_step12=_iterator12.n()).done;){var loader=_step12.value;var _iterator13=_createForOfIteratorHelper(loader.extensions),_step13;try{for(_iterator13.s();!(_step13=_iterator13.n()).done;){var loaderExtension=_step13.value;if(loaderExtension.toLowerCase()===extension){return loader;}}}catch(err){_iterator13.e(err);}finally{_iterator13.f();}}}catch(err){_iterator12.e(err);}finally{_iterator12.f();}return null;}function findLoaderByMIMEType(loaders,mimeType){var _iterator14=_createForOfIteratorHelper(loaders),_step14;try{for(_iterator14.s();!(_step14=_iterator14.n()).done;){var loader=_step14.value;if(loader.mimeTypes&&loader.mimeTypes.includes(mimeType)){return loader;}if(mimeType==="application/x.".concat(loader.id)){return loader;}}}catch(err){_iterator14.e(err);}finally{_iterator14.f();}return null;}function findLoaderByInitialBytes(loaders,data){if(!data){return null;}var _iterator15=_createForOfIteratorHelper(loaders),_step15;try{for(_iterator15.s();!(_step15=_iterator15.n()).done;){var loader=_step15.value;if(typeof data==='string'){if(testDataAgainstText(data,loader)){return loader;}}else if(ArrayBuffer.isView(data)){if(testDataAgainstBinary(data.buffer,data.byteOffset,loader)){return loader;}}else if(data instanceof ArrayBuffer){var byteOffset=0;if(testDataAgainstBinary(data,byteOffset,loader)){return loader;}}}}catch(err){_iterator15.e(err);}finally{_iterator15.f();}return null;}function testDataAgainstText(data,loader){if(loader.testText){return loader.testText(data);}var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(function(test){return data.startsWith(test);});}function testDataAgainstBinary(data,byteOffset,loader){var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(function(test){return testBinary(data,byteOffset,loader,test);});}function testBinary(data,byteOffset,loader,test){if(test instanceof ArrayBuffer){return compareArrayBuffers(test,data,test.byteLength);}switch(_typeof(test)){case'function':return test(data,loader);case'string':var magic=getMagicString$1(data,byteOffset,test.length);return test===magic;default:return false;}}function getFirstCharacters(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$1(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$1(data,byteOffset,length);}return'';}function getMagicString$1(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength1&&_args5[1]!==undefined?_args5[1]:{};_options$chunkSize=options.chunkSize,chunkSize=_options$chunkSize===void 0?DEFAULT_CHUNK_SIZE$1:_options$chunkSize;byteOffset=0;case 3:if(!(byteOffset2&&arguments[2]!==undefined?arguments[2]:null;if(previousContext){return previousContext;}var resolvedContext=_objectSpread({fetch:getFetchFunction(options,context)},context);if(!Array.isArray(resolvedContext.loaders)){resolvedContext.loaders=null;}return resolvedContext;}function getLoadersFromContext(loaders,context){if(!context&&loaders&&!Array.isArray(loaders)){return loaders;}var candidateLoaders;if(loaders){candidateLoaders=Array.isArray(loaders)?loaders:[loaders];}if(context&&context.loaders){var contextLoaders=Array.isArray(context.loaders)?context.loaders:[context.loaders];candidateLoaders=candidateLoaders?[].concat(_toConsumableArray(candidateLoaders),_toConsumableArray(contextLoaders)):contextLoaders;}return candidateLoaders&&candidateLoaders.length?candidateLoaders:null;}function parse$3(_x31,_x32,_x33,_x34){return _parse$.apply(this,arguments);}function _parse$(){_parse$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee19(data,loaders,options,context){var _getResourceUrlAndTyp4,url,typedLoaders,candidateLoaders,loader;return _regeneratorRuntime().wrap(function _callee19$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:assert$4(!context||_typeof(context)==='object');if(loaders&&!Array.isArray(loaders)&&!isLoaderObject(loaders)){context=undefined;options=loaders;loaders=undefined;}_context23.next=4;return data;case 4:data=_context23.sent;options=options||{};_getResourceUrlAndTyp4=getResourceUrlAndType(data),url=_getResourceUrlAndTyp4.url;typedLoaders=loaders;candidateLoaders=getLoadersFromContext(typedLoaders,context);_context23.next=11;return selectLoader(data,candidateLoaders,options);case 11:loader=_context23.sent;if(loader){_context23.next=14;break;}return _context23.abrupt("return",null);case 14:options=normalizeOptions(options,loader,candidateLoaders,url);context=getLoaderContext({url:url,parse:parse$3,loaders:candidateLoaders},options,context);_context23.next=18;return parseWithLoader(loader,data,options,context);case 18:return _context23.abrupt("return",_context23.sent);case 19:case"end":return _context23.stop();}}},_callee19);}));return _parse$.apply(this,arguments);}function parseWithLoader(_x35,_x36,_x37,_x38){return _parseWithLoader.apply(this,arguments);}function _parseWithLoader(){_parseWithLoader=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee20(loader,data,options,context){var response,ok,redirected,status,statusText,type,url,headers;return _regeneratorRuntime().wrap(function _callee20$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:validateWorkerVersion(loader);if(isResponse(data)){response=data;ok=response.ok,redirected=response.redirected,status=response.status,statusText=response.statusText,type=response.type,url=response.url;headers=Object.fromEntries(response.headers.entries());context.response={headers:headers,ok:ok,redirected:redirected,status:status,statusText:statusText,type:type,url:url};}_context24.next=4;return getArrayBufferOrStringFromData(data,loader,options);case 4:data=_context24.sent;if(!(loader.parseTextSync&&typeof data==='string')){_context24.next=8;break;}options.dataType='text';return _context24.abrupt("return",loader.parseTextSync(data,options,context,loader));case 8:if(!canParseWithWorker(loader,options)){_context24.next=12;break;}_context24.next=11;return parseWithWorker(loader,data,options,context,parse$3);case 11:return _context24.abrupt("return",_context24.sent);case 12:if(!(loader.parseText&&typeof data==='string')){_context24.next=16;break;}_context24.next=15;return loader.parseText(data,options,context,loader);case 15:return _context24.abrupt("return",_context24.sent);case 16:if(!loader.parse){_context24.next=20;break;}_context24.next=19;return loader.parse(data,options,context,loader);case 19:return _context24.abrupt("return",_context24.sent);case 20:assert$4(!loader.parseSync);throw new Error("".concat(loader.id," loader - no parser found and worker is disabled"));case 22:case"end":return _context24.stop();}}},_callee20);}));return _parseWithLoader.apply(this,arguments);}var VERSION$5="3.2.6";var VERSION$4="3.2.6";var VERSION$3="3.2.6";var BASIS_CDN_ENCODER_WASM="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$3,"/dist/libs/basis_encoder.wasm");var BASIS_CDN_ENCODER_JS="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$3,"/dist/libs/basis_encoder.js");var loadBasisTranscoderPromise;function loadBasisTrascoderModule(_x39){return _loadBasisTrascoderModule.apply(this,arguments);}function _loadBasisTrascoderModule(){_loadBasisTrascoderModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee21(options){var modules;return _regeneratorRuntime().wrap(function _callee21$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:modules=options.modules||{};if(!modules.basis){_context25.next=3;break;}return _context25.abrupt("return",modules.basis);case 3:loadBasisTranscoderPromise=loadBasisTranscoderPromise||loadBasisTrascoder(options);_context25.next=6;return loadBasisTranscoderPromise;case 6:return _context25.abrupt("return",_context25.sent);case 7:case"end":return _context25.stop();}}},_callee21);}));return _loadBasisTrascoderModule.apply(this,arguments);}function loadBasisTrascoder(_x40){return _loadBasisTrascoder.apply(this,arguments);}function _loadBasisTrascoder(){_loadBasisTrascoder=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee22(options){var BASIS,wasmBinary,_yield$Promise$all,_yield$Promise$all2;return _regeneratorRuntime().wrap(function _callee22$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:BASIS=null;wasmBinary=null;_context26.t0=Promise;_context26.next=5;return loadLibrary('basis_transcoder.js','textures',options);case 5:_context26.t1=_context26.sent;_context26.next=8;return loadLibrary('basis_transcoder.wasm','textures',options);case 8:_context26.t2=_context26.sent;_context26.t3=[_context26.t1,_context26.t2];_context26.next=12;return _context26.t0.all.call(_context26.t0,_context26.t3);case 12:_yield$Promise$all=_context26.sent;_yield$Promise$all2=_slicedToArray(_yield$Promise$all,2);BASIS=_yield$Promise$all2[0];wasmBinary=_yield$Promise$all2[1];BASIS=BASIS||globalThis.BASIS;_context26.next=19;return initializeBasisTrascoderModule(BASIS,wasmBinary);case 19:return _context26.abrupt("return",_context26.sent);case 20:case"end":return _context26.stop();}}},_callee22);}));return _loadBasisTrascoder.apply(this,arguments);}function initializeBasisTrascoderModule(BasisModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(function(resolve){BasisModule(options).then(function(module){var BasisFile=module.BasisFile,initializeBasis=module.initializeBasis;initializeBasis();resolve({BasisFile:BasisFile});});});}var loadBasisEncoderPromise;function loadBasisEncoderModule(_x41){return _loadBasisEncoderModule.apply(this,arguments);}function _loadBasisEncoderModule(){_loadBasisEncoderModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee23(options){var modules;return _regeneratorRuntime().wrap(function _callee23$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:modules=options.modules||{};if(!modules.basisEncoder){_context27.next=3;break;}return _context27.abrupt("return",modules.basisEncoder);case 3:loadBasisEncoderPromise=loadBasisEncoderPromise||loadBasisEncoder(options);_context27.next=6;return loadBasisEncoderPromise;case 6:return _context27.abrupt("return",_context27.sent);case 7:case"end":return _context27.stop();}}},_callee23);}));return _loadBasisEncoderModule.apply(this,arguments);}function loadBasisEncoder(_x42){return _loadBasisEncoder.apply(this,arguments);}function _loadBasisEncoder(){_loadBasisEncoder=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee24(options){var BASIS_ENCODER,wasmBinary,_yield$Promise$all3,_yield$Promise$all4;return _regeneratorRuntime().wrap(function _callee24$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:BASIS_ENCODER=null;wasmBinary=null;_context28.t0=Promise;_context28.next=5;return loadLibrary(BASIS_CDN_ENCODER_JS,'textures',options);case 5:_context28.t1=_context28.sent;_context28.next=8;return loadLibrary(BASIS_CDN_ENCODER_WASM,'textures',options);case 8:_context28.t2=_context28.sent;_context28.t3=[_context28.t1,_context28.t2];_context28.next=12;return _context28.t0.all.call(_context28.t0,_context28.t3);case 12:_yield$Promise$all3=_context28.sent;_yield$Promise$all4=_slicedToArray(_yield$Promise$all3,2);BASIS_ENCODER=_yield$Promise$all4[0];wasmBinary=_yield$Promise$all4[1];BASIS_ENCODER=BASIS_ENCODER||globalThis.BASIS;_context28.next=19;return initializeBasisEncoderModule(BASIS_ENCODER,wasmBinary);case 19:return _context28.abrupt("return",_context28.sent);case 20:case"end":return _context28.stop();}}},_callee24);}));return _loadBasisEncoder.apply(this,arguments);}function initializeBasisEncoderModule(BasisEncoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(function(resolve){BasisEncoderModule(options).then(function(module){var BasisFile=module.BasisFile,KTX2File=module.KTX2File,initializeBasis=module.initializeBasis,BasisEncoder=module.BasisEncoder;initializeBasis();resolve({BasisFile:BasisFile,KTX2File:KTX2File,BasisEncoder:BasisEncoder});});});}var GL_EXTENSIONS_CONSTANTS={COMPRESSED_RGB_S3TC_DXT1_EXT:0x83f0,COMPRESSED_RGBA_S3TC_DXT1_EXT:0x83f1,COMPRESSED_RGBA_S3TC_DXT3_EXT:0x83f2,COMPRESSED_RGBA_S3TC_DXT5_EXT:0x83f3,COMPRESSED_R11_EAC:0x9270,COMPRESSED_SIGNED_R11_EAC:0x9271,COMPRESSED_RG11_EAC:0x9272,COMPRESSED_SIGNED_RG11_EAC:0x9273,COMPRESSED_RGB8_ETC2:0x9274,COMPRESSED_RGBA8_ETC2_EAC:0x9275,COMPRESSED_SRGB8_ETC2:0x9276,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:0x9277,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9278,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9279,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:0x8c00,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:0x8c02,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:0x8c01,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:0x8c03,COMPRESSED_RGB_ETC1_WEBGL:0x8d64,COMPRESSED_RGB_ATC_WEBGL:0x8c92,COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:0x8c93,COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:0x87ee,COMPRESSED_RGBA_ASTC_4X4_KHR:0x93b0,COMPRESSED_RGBA_ASTC_5X4_KHR:0x93b1,COMPRESSED_RGBA_ASTC_5X5_KHR:0x93b2,COMPRESSED_RGBA_ASTC_6X5_KHR:0x93b3,COMPRESSED_RGBA_ASTC_6X6_KHR:0x93b4,COMPRESSED_RGBA_ASTC_8X5_KHR:0x93b5,COMPRESSED_RGBA_ASTC_8X6_KHR:0x93b6,COMPRESSED_RGBA_ASTC_8X8_KHR:0x93b7,COMPRESSED_RGBA_ASTC_10X5_KHR:0x93b8,COMPRESSED_RGBA_ASTC_10X6_KHR:0x93b9,COMPRESSED_RGBA_ASTC_10X8_KHR:0x93ba,COMPRESSED_RGBA_ASTC_10X10_KHR:0x93bb,COMPRESSED_RGBA_ASTC_12X10_KHR:0x93bc,COMPRESSED_RGBA_ASTC_12X12_KHR:0x93bd,COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR:0x93d0,COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR:0x93d1,COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR:0x93d2,COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR:0x93d3,COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR:0x93d4,COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR:0x93d5,COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR:0x93d6,COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR:0x93d7,COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR:0x93d8,COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR:0x93d9,COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR:0x93da,COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR:0x93db,COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR:0x93dc,COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR:0x93dd,COMPRESSED_RED_RGTC1_EXT:0x8dbb,COMPRESSED_SIGNED_RED_RGTC1_EXT:0x8dbc,COMPRESSED_RED_GREEN_RGTC2_EXT:0x8dbd,COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:0x8dbe,COMPRESSED_SRGB_S3TC_DXT1_EXT:0x8c4c,COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:0x8c4d,COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:0x8c4e,COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:0x8c4f};var BROWSER_PREFIXES=['','WEBKIT_','MOZ_'];var WEBGL_EXTENSIONS={WEBGL_compressed_texture_s3tc:'dxt',WEBGL_compressed_texture_s3tc_srgb:'dxt-srgb',WEBGL_compressed_texture_etc1:'etc1',WEBGL_compressed_texture_etc:'etc2',WEBGL_compressed_texture_pvrtc:'pvrtc',WEBGL_compressed_texture_atc:'atc',WEBGL_compressed_texture_astc:'astc',EXT_texture_compression_rgtc:'rgtc'};var formats=null;function getSupportedGPUTextureFormats(gl){if(!formats){gl=gl||getWebGLContext()||undefined;formats=new Set();var _iterator16=_createForOfIteratorHelper(BROWSER_PREFIXES),_step16;try{for(_iterator16.s();!(_step16=_iterator16.n()).done;){var prefix=_step16.value;for(var extension in WEBGL_EXTENSIONS){if(gl&&gl.getExtension("".concat(prefix).concat(extension))){var gpuTextureFormat=WEBGL_EXTENSIONS[extension];formats.add(gpuTextureFormat);}}}}catch(err){_iterator16.e(err);}finally{_iterator16.f();}}return formats;}function getWebGLContext(){try{var _canvas6=document.createElement('canvas');return _canvas6.getContext('webgl');}catch(error){return null;}}var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f||(f={}));var KTX2_ID=[0xab,0x4b,0x54,0x58,0x20,0x32,0x30,0xbb,0x0d,0x0a,0x1a,0x0a];function isKTX(data){var id=new Uint8Array(data);var notKTX=id.byteLength1&&_args27[1]!==undefined?_args27[1]:null;if(isEmptyObject(imagebitmapOptions)||!imagebitmapOptionsSupported){imagebitmapOptions=null;}if(!imagebitmapOptions){_context33.next=13;break;}_context33.prev=3;_context33.next=6;return createImageBitmap(blob,imagebitmapOptions);case 6:return _context33.abrupt("return",_context33.sent);case 9:_context33.prev=9;_context33.t0=_context33["catch"](3);console.warn(_context33.t0);imagebitmapOptionsSupported=false;case 13:_context33.next=15;return createImageBitmap(blob);case 15:return _context33.abrupt("return",_context33.sent);case 16:case"end":return _context33.stop();}}},_callee29,null,[[3,9]]);}));return _safeCreateImageBitmap.apply(this,arguments);}function isEmptyObject(object){for(var key in object||EMPTY_OBJECT){return false;}return true;}var BIG_ENDIAN=false;var LITTLE_ENDIAN=true;function getBinaryImageMetadata(binaryData){var dataView=toDataView(binaryData);return getPngMetadata(dataView)||getJpegMetadata(dataView)||getGifMetadata(dataView)||getBmpMetadata(dataView);}function getPngMetadata(binaryData){var dataView=toDataView(binaryData);var isPng=dataView.byteLength>=24&&dataView.getUint32(0,BIG_ENDIAN)===0x89504e47;if(!isPng){return null;}return{mimeType:'image/png',width:dataView.getUint32(16,BIG_ENDIAN),height:dataView.getUint32(20,BIG_ENDIAN)};}function getGifMetadata(binaryData){var dataView=toDataView(binaryData);var isGif=dataView.byteLength>=10&&dataView.getUint32(0,BIG_ENDIAN)===0x47494638;if(!isGif){return null;}return{mimeType:'image/gif',width:dataView.getUint16(6,LITTLE_ENDIAN),height:dataView.getUint16(8,LITTLE_ENDIAN)};}function getBmpMetadata(binaryData){var dataView=toDataView(binaryData);var isBmp=dataView.byteLength>=14&&dataView.getUint16(0,BIG_ENDIAN)===0x424d&&dataView.getUint32(2,LITTLE_ENDIAN)===dataView.byteLength;if(!isBmp){return null;}return{mimeType:'image/bmp',width:dataView.getUint32(18,LITTLE_ENDIAN),height:dataView.getUint32(22,LITTLE_ENDIAN)};}function getJpegMetadata(binaryData){var dataView=toDataView(binaryData);var isJpeg=dataView.byteLength>=3&&dataView.getUint16(0,BIG_ENDIAN)===0xffd8&&dataView.getUint8(2)===0xff;if(!isJpeg){return null;}var _getJpegMarkers=getJpegMarkers(),tableMarkers=_getJpegMarkers.tableMarkers,sofMarkers=_getJpegMarkers.sofMarkers;var i=2;while(i+9=0&&byteLength<=bufferView.byteLength);return{ArrayType:ArrayType,length:length,byteLength:byteLength};}var DEFAULT_GLTF_JSON={asset:{version:'2.0',generator:'loaders.gl'},buffers:[]};var GLTFScenegraph=/*#__PURE__*/function(){function GLTFScenegraph(gltf){_classCallCheck(this,GLTFScenegraph);_defineProperty(this,"gltf",void 0);_defineProperty(this,"sourceBuffers",void 0);_defineProperty(this,"byteLength",void 0);this.gltf=gltf||{json:_objectSpread({},DEFAULT_GLTF_JSON),buffers:[]};this.sourceBuffers=[];this.byteLength=0;if(this.gltf.buffers&&this.gltf.buffers[0]){this.byteLength=this.gltf.buffers[0].byteLength;this.sourceBuffers=[this.gltf.buffers[0]];}}_createClass(GLTFScenegraph,[{key:"json",get:function get(){return this.gltf.json;}},{key:"getApplicationData",value:function getApplicationData(key){var data=this.json[key];return data;}},{key:"getExtraData",value:function getExtraData(key){var extras=this.json.extras||{};return extras[key];}},{key:"getExtension",value:function getExtension(extensionName){var isExtension=this.getUsedExtensions().find(function(name){return name===extensionName;});var extensions=this.json.extensions||{};return isExtension?extensions[extensionName]||true:null;}},{key:"getRequiredExtension",value:function getRequiredExtension(extensionName){var isRequired=this.getRequiredExtensions().find(function(name){return name===extensionName;});return isRequired?this.getExtension(extensionName):null;}},{key:"getRequiredExtensions",value:function getRequiredExtensions(){return this.json.extensionsRequired||[];}},{key:"getUsedExtensions",value:function getUsedExtensions(){return this.json.extensionsUsed||[];}},{key:"getObjectExtension",value:function getObjectExtension(object,extensionName){var extensions=object.extensions||{};return extensions[extensionName];}},{key:"getScene",value:function getScene(index){return this.getObject('scenes',index);}},{key:"getNode",value:function getNode(index){return this.getObject('nodes',index);}},{key:"getSkin",value:function getSkin(index){return this.getObject('skins',index);}},{key:"getMesh",value:function getMesh(index){return this.getObject('meshes',index);}},{key:"getMaterial",value:function getMaterial(index){return this.getObject('materials',index);}},{key:"getAccessor",value:function getAccessor(index){return this.getObject('accessors',index);}},{key:"getTexture",value:function getTexture(index){return this.getObject('textures',index);}},{key:"getSampler",value:function getSampler(index){return this.getObject('samplers',index);}},{key:"getImage",value:function getImage(index){return this.getObject('images',index);}},{key:"getBufferView",value:function getBufferView(index){return this.getObject('bufferViews',index);}},{key:"getBuffer",value:function getBuffer(index){return this.getObject('buffers',index);}},{key:"getObject",value:function getObject(array,index){if(_typeof(index)==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){throw new Error("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}},{key:"getTypedArrayForBufferView",value:function getTypedArrayForBufferView(bufferView){bufferView=this.getBufferView(bufferView);var bufferIndex=bufferView.buffer;var binChunk=this.gltf.buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}},{key:"getTypedArrayForAccessor",value:function getTypedArrayForAccessor(accessor){accessor=this.getAccessor(accessor);var bufferView=this.getBufferView(accessor.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var _getAccessorArrayType=getAccessorArrayTypeAndLength(accessor,bufferView),ArrayType=_getAccessorArrayType.ArrayType,length=_getAccessorArrayType.length;var byteOffset=bufferView.byteOffset+accessor.byteOffset;return new ArrayType(arrayBuffer,byteOffset,length);}},{key:"getTypedArrayForImageData",value:function getTypedArrayForImageData(image){image=this.getAccessor(image);var bufferView=this.getBufferView(image.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var byteOffset=bufferView.byteOffset||0;return new Uint8Array(arrayBuffer,byteOffset,bufferView.byteLength);}},{key:"addApplicationData",value:function addApplicationData(key,data){this.json[key]=data;return this;}},{key:"addExtraData",value:function addExtraData(key,data){this.json.extras=this.json.extras||{};this.json.extras[key]=data;return this;}},{key:"addObjectExtension",value:function addObjectExtension(object,extensionName,data){object.extensions=object.extensions||{};object.extensions[extensionName]=data;this.registerUsedExtension(extensionName);return this;}},{key:"setObjectExtension",value:function setObjectExtension(object,extensionName,data){var extensions=object.extensions||{};extensions[extensionName]=data;}},{key:"removeObjectExtension",value:function removeObjectExtension(object,extensionName){var extensions=object.extensions||{};var extension=extensions[extensionName];delete extensions[extensionName];return extension;}},{key:"addExtension",value:function addExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.json.extensions=this.json.extensions||{};this.json.extensions[extensionName]=extensionData;this.registerUsedExtension(extensionName);return extensionData;}},{key:"addRequiredExtension",value:function addRequiredExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.addExtension(extensionName,extensionData);this.registerRequiredExtension(extensionName);return extensionData;}},{key:"registerUsedExtension",value:function registerUsedExtension(extensionName){this.json.extensionsUsed=this.json.extensionsUsed||[];if(!this.json.extensionsUsed.find(function(ext){return ext===extensionName;})){this.json.extensionsUsed.push(extensionName);}}},{key:"registerRequiredExtension",value:function registerRequiredExtension(extensionName){this.registerUsedExtension(extensionName);this.json.extensionsRequired=this.json.extensionsRequired||[];if(!this.json.extensionsRequired.find(function(ext){return ext===extensionName;})){this.json.extensionsRequired.push(extensionName);}}},{key:"removeExtension",value:function removeExtension(extensionName){if(this.json.extensionsRequired){this._removeStringFromArray(this.json.extensionsRequired,extensionName);}if(this.json.extensionsUsed){this._removeStringFromArray(this.json.extensionsUsed,extensionName);}if(this.json.extensions){delete this.json.extensions[extensionName];}}},{key:"setDefaultScene",value:function setDefaultScene(sceneIndex){this.json.scene=sceneIndex;}},{key:"addScene",value:function addScene(scene){var nodeIndices=scene.nodeIndices;this.json.scenes=this.json.scenes||[];this.json.scenes.push({nodes:nodeIndices});return this.json.scenes.length-1;}},{key:"addNode",value:function addNode(node){var meshIndex=node.meshIndex,matrix=node.matrix;this.json.nodes=this.json.nodes||[];var nodeData={mesh:meshIndex};if(matrix){nodeData.matrix=matrix;}this.json.nodes.push(nodeData);return this.json.nodes.length-1;}},{key:"addMesh",value:function addMesh(mesh){var attributes=mesh.attributes,indices=mesh.indices,material=mesh.material,_mesh$mode=mesh.mode,mode=_mesh$mode===void 0?4:_mesh$mode;var accessors=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessors,mode:mode}]};if(indices){var indicesAccessor=this._addIndices(indices);glTFMesh.primitives[0].indices=indicesAccessor;}if(Number.isFinite(material)){glTFMesh.primitives[0].material=material;}this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}},{key:"addPointCloud",value:function addPointCloud(attributes){var accessorIndices=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessorIndices,mode:0}]};this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}},{key:"addImage",value:function addImage(imageData,mimeTypeOpt){var metadata=getBinaryImageMetadata(imageData);var mimeType=mimeTypeOpt||(metadata===null||metadata===void 0?void 0:metadata.mimeType);var bufferViewIndex=this.addBufferView(imageData);var glTFImage={bufferView:bufferViewIndex,mimeType:mimeType};this.json.images=this.json.images||[];this.json.images.push(glTFImage);return this.json.images.length-1;}},{key:"addBufferView",value:function addBufferView(buffer){var byteLength=buffer.byteLength;assert$1(Number.isFinite(byteLength));this.sourceBuffers=this.sourceBuffers||[];this.sourceBuffers.push(buffer);var glTFBufferView={buffer:0,byteOffset:this.byteLength,byteLength:byteLength};this.byteLength+=padToNBytes(byteLength,4);this.json.bufferViews=this.json.bufferViews||[];this.json.bufferViews.push(glTFBufferView);return this.json.bufferViews.length-1;}},{key:"addAccessor",value:function addAccessor(bufferViewIndex,accessor){var glTFAccessor={bufferView:bufferViewIndex,type:getAccessorTypeFromSize(accessor.size),componentType:accessor.componentType,count:accessor.count,max:accessor.max,min:accessor.min};this.json.accessors=this.json.accessors||[];this.json.accessors.push(glTFAccessor);return this.json.accessors.length-1;}},{key:"addBinaryBuffer",value:function addBinaryBuffer(sourceBuffer){var accessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{size:3};var bufferViewIndex=this.addBufferView(sourceBuffer);var minMax={min:accessor.min,max:accessor.max};if(!minMax.min||!minMax.max){minMax=this._getAccessorMinMax(sourceBuffer,accessor.size);}var accessorDefaults={size:accessor.size,componentType:getComponentTypeFromArray(sourceBuffer),count:Math.round(sourceBuffer.length/accessor.size),min:minMax.min,max:minMax.max};return this.addAccessor(bufferViewIndex,Object.assign(accessorDefaults,accessor));}},{key:"addTexture",value:function addTexture(texture){var imageIndex=texture.imageIndex;var glTFTexture={source:imageIndex};this.json.textures=this.json.textures||[];this.json.textures.push(glTFTexture);return this.json.textures.length-1;}},{key:"addMaterial",value:function addMaterial(pbrMaterialInfo){this.json.materials=this.json.materials||[];this.json.materials.push(pbrMaterialInfo);return this.json.materials.length-1;}},{key:"createBinaryChunk",value:function createBinaryChunk(){var _this$json,_this$json$buffers;this.gltf.buffers=[];var totalByteLength=this.byteLength;var arrayBuffer=new ArrayBuffer(totalByteLength);var targetArray=new Uint8Array(arrayBuffer);var dstByteOffset=0;var _iterator17=_createForOfIteratorHelper(this.sourceBuffers||[]),_step17;try{for(_iterator17.s();!(_step17=_iterator17.n()).done;){var sourceBuffer=_step17.value;dstByteOffset=copyToArray(sourceBuffer,targetArray,dstByteOffset);}}catch(err){_iterator17.e(err);}finally{_iterator17.f();}if((_this$json=this.json)!==null&&_this$json!==void 0&&(_this$json$buffers=_this$json.buffers)!==null&&_this$json$buffers!==void 0&&_this$json$buffers[0]){this.json.buffers[0].byteLength=totalByteLength;}else{this.json.buffers=[{byteLength:totalByteLength}];}this.gltf.binary=arrayBuffer;this.sourceBuffers=[arrayBuffer];}},{key:"_removeStringFromArray",value:function _removeStringFromArray(array,string){var found=true;while(found){var index=array.indexOf(string);if(index>-1){array.splice(index,1);}else{found=false;}}}},{key:"_addAttributes",value:function _addAttributes(){var attributes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var result={};for(var attributeKey in attributes){var attributeData=attributes[attributeKey];var attrName=this._getGltfAttributeName(attributeKey);var accessor=this.addBinaryBuffer(attributeData.value,attributeData);result[attrName]=accessor;}return result;}},{key:"_addIndices",value:function _addIndices(indices){return this.addBinaryBuffer(indices,{size:1});}},{key:"_getGltfAttributeName",value:function _getGltfAttributeName(attributeName){switch(attributeName.toLowerCase()){case'position':case'positions':case'vertices':return'POSITION';case'normal':case'normals':return'NORMAL';case'color':case'colors':return'COLOR_0';case'texcoord':case'texcoords':return'TEXCOORD_0';default:return attributeName;}}},{key:"_getAccessorMinMax",value:function _getAccessorMinMax(buffer,size){var result={min:null,max:null};if(buffer.length5&&_args30[5]!==undefined?_args30[5]:'NONE';_context36.next=3;return loadWasmInstance();case 3:instance=_context36.sent;decode$5(instance,instance.exports[DECODERS[mode]],target,count,size,source,instance.exports[FILTERS[filter||'NONE']]);case 5:case"end":return _context36.stop();}}},_callee32);}));return _meshoptDecodeGltfBuffer.apply(this,arguments);}var wasmPromise;function loadWasmInstance(){return _loadWasmInstance.apply(this,arguments);}function _loadWasmInstance(){_loadWasmInstance=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee33(){return _regeneratorRuntime().wrap(function _callee33$(_context37){while(1){switch(_context37.prev=_context37.next){case 0:if(!wasmPromise){wasmPromise=loadWasmModule();}return _context37.abrupt("return",wasmPromise);case 2:case"end":return _context37.stop();}}},_callee33);}));return _loadWasmInstance.apply(this,arguments);}function loadWasmModule(){return _loadWasmModule.apply(this,arguments);}function _loadWasmModule(){_loadWasmModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee34(){var wasm,result;return _regeneratorRuntime().wrap(function _callee34$(_context38){while(1){switch(_context38.prev=_context38.next){case 0:wasm=wasm_base;if(WebAssembly.validate(detector)){wasm=wasm_simd;console.log('Warning: meshopt_decoder is using experimental SIMD support');}_context38.next=4;return WebAssembly.instantiate(unpack(wasm),{});case 4:result=_context38.sent;_context38.next=7;return result.instance.exports.__wasm_call_ctors();case 7:return _context38.abrupt("return",result.instance);case 8:case"end":return _context38.stop();}}},_callee34);}));return _loadWasmModule.apply(this,arguments);}function unpack(data){var result=new Uint8Array(data.length);for(var _i499=0;_i49996?ch-71:ch>64?ch-65:ch>47?ch+4:ch>46?63:62;}var write=0;for(var _i500=0;_i500maxX?x:maxX;maxY=y>maxY?y:maxY;maxZ=_z4>maxZ?_z4:maxZ;}return[[minX,minY,minZ],[maxX,maxY,maxZ]];}function assert(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}var Schema=/*#__PURE__*/function(){function Schema(fields,metadata){_classCallCheck(this,Schema);_defineProperty(this,"fields",void 0);_defineProperty(this,"metadata",void 0);assert(Array.isArray(fields));checkNames(fields);this.fields=fields;this.metadata=metadata||new Map();}_createClass(Schema,[{key:"compareTo",value:function compareTo(other){if(this.metadata!==other.metadata){return false;}if(this.fields.length!==other.fields.length){return false;}for(var _i502=0;_i5022&&arguments[2]!==undefined?arguments[2]:false;var metadata=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Map();_classCallCheck(this,Field);_defineProperty(this,"name",void 0);_defineProperty(this,"type",void 0);_defineProperty(this,"nullable",void 0);_defineProperty(this,"metadata",void 0);this.name=name;this.type=type;this.nullable=nullable;this.metadata=metadata;}_createClass(Field,[{key:"typeId",get:function get(){return this.type&&this.type.typeId;}},{key:"clone",value:function clone(){return new Field(this.name,this.type,this.nullable,this.metadata);}},{key:"compareTo",value:function compareTo(other){return this.name===other.name&&this.type===other.type&&this.nullable===other.nullable&&this.metadata===other.metadata;}},{key:"toString",value:function toString(){return"".concat(this.type).concat(this.nullable?', nullable':'').concat(this.metadata?", metadata: ".concat(this.metadata):'');}}]);return Field;}();var Type;(function(Type){Type[Type["NONE"]=0]="NONE";Type[Type["Null"]=1]="Null";Type[Type["Int"]=2]="Int";Type[Type["Float"]=3]="Float";Type[Type["Binary"]=4]="Binary";Type[Type["Utf8"]=5]="Utf8";Type[Type["Bool"]=6]="Bool";Type[Type["Decimal"]=7]="Decimal";Type[Type["Date"]=8]="Date";Type[Type["Time"]=9]="Time";Type[Type["Timestamp"]=10]="Timestamp";Type[Type["Interval"]=11]="Interval";Type[Type["List"]=12]="List";Type[Type["Struct"]=13]="Struct";Type[Type["Union"]=14]="Union";Type[Type["FixedSizeBinary"]=15]="FixedSizeBinary";Type[Type["FixedSizeList"]=16]="FixedSizeList";Type[Type["Map"]=17]="Map";Type[Type["Dictionary"]=-1]="Dictionary";Type[Type["Int8"]=-2]="Int8";Type[Type["Int16"]=-3]="Int16";Type[Type["Int32"]=-4]="Int32";Type[Type["Int64"]=-5]="Int64";Type[Type["Uint8"]=-6]="Uint8";Type[Type["Uint16"]=-7]="Uint16";Type[Type["Uint32"]=-8]="Uint32";Type[Type["Uint64"]=-9]="Uint64";Type[Type["Float16"]=-10]="Float16";Type[Type["Float32"]=-11]="Float32";Type[Type["Float64"]=-12]="Float64";Type[Type["DateDay"]=-13]="DateDay";Type[Type["DateMillisecond"]=-14]="DateMillisecond";Type[Type["TimestampSecond"]=-15]="TimestampSecond";Type[Type["TimestampMillisecond"]=-16]="TimestampMillisecond";Type[Type["TimestampMicrosecond"]=-17]="TimestampMicrosecond";Type[Type["TimestampNanosecond"]=-18]="TimestampNanosecond";Type[Type["TimeSecond"]=-19]="TimeSecond";Type[Type["TimeMillisecond"]=-20]="TimeMillisecond";Type[Type["TimeMicrosecond"]=-21]="TimeMicrosecond";Type[Type["TimeNanosecond"]=-22]="TimeNanosecond";Type[Type["DenseUnion"]=-23]="DenseUnion";Type[Type["SparseUnion"]=-24]="SparseUnion";Type[Type["IntervalDayTime"]=-25]="IntervalDayTime";Type[Type["IntervalYearMonth"]=-26]="IntervalYearMonth";})(Type||(Type={}));var _Symbol$toStringTag,_Symbol$toStringTag2,_Symbol$toStringTag7;var DataType=/*#__PURE__*/function(){function DataType(){_classCallCheck(this,DataType);}_createClass(DataType,[{key:"typeId",get:function get(){return Type.NONE;}},{key:"compareTo",value:function compareTo(other){return this===other;}}],[{key:"isNull",value:function isNull(x){return x&&x.typeId===Type.Null;}},{key:"isInt",value:function isInt(x){return x&&x.typeId===Type.Int;}},{key:"isFloat",value:function isFloat(x){return x&&x.typeId===Type.Float;}},{key:"isBinary",value:function isBinary(x){return x&&x.typeId===Type.Binary;}},{key:"isUtf8",value:function isUtf8(x){return x&&x.typeId===Type.Utf8;}},{key:"isBool",value:function isBool(x){return x&&x.typeId===Type.Bool;}},{key:"isDecimal",value:function isDecimal(x){return x&&x.typeId===Type.Decimal;}},{key:"isDate",value:function isDate(x){return x&&x.typeId===Type.Date;}},{key:"isTime",value:function isTime(x){return x&&x.typeId===Type.Time;}},{key:"isTimestamp",value:function isTimestamp(x){return x&&x.typeId===Type.Timestamp;}},{key:"isInterval",value:function isInterval(x){return x&&x.typeId===Type.Interval;}},{key:"isList",value:function isList(x){return x&&x.typeId===Type.List;}},{key:"isStruct",value:function isStruct(x){return x&&x.typeId===Type.Struct;}},{key:"isUnion",value:function isUnion(x){return x&&x.typeId===Type.Union;}},{key:"isFixedSizeBinary",value:function isFixedSizeBinary(x){return x&&x.typeId===Type.FixedSizeBinary;}},{key:"isFixedSizeList",value:function isFixedSizeList(x){return x&&x.typeId===Type.FixedSizeList;}},{key:"isMap",value:function isMap(x){return x&&x.typeId===Type.Map;}},{key:"isDictionary",value:function isDictionary(x){return x&&x.typeId===Type.Dictionary;}}]);return DataType;}();_Symbol$toStringTag=Symbol.toStringTag;var Int=/*#__PURE__*/function(_DataType,_Symbol$toStringTag3){_inherits(Int,_DataType);var _super140=_createSuper(Int);function Int(isSigned,bitWidth){var _this117;_classCallCheck(this,Int);_this117=_super140.call(this);_defineProperty(_assertThisInitialized(_this117),"isSigned",void 0);_defineProperty(_assertThisInitialized(_this117),"bitWidth",void 0);_this117.isSigned=isSigned;_this117.bitWidth=bitWidth;return _this117;}_createClass(Int,[{key:"typeId",get:function get(){return Type.Int;}},{key:_Symbol$toStringTag3,get:function get(){return'Int';}},{key:"toString",value:function toString(){return"".concat(this.isSigned?'I':'Ui',"nt").concat(this.bitWidth);}}]);return Int;}(DataType,_Symbol$toStringTag);var Int8=/*#__PURE__*/function(_Int){_inherits(Int8,_Int);var _super141=_createSuper(Int8);function Int8(){_classCallCheck(this,Int8);return _super141.call(this,true,8);}return _createClass(Int8);}(Int);var Int16=/*#__PURE__*/function(_Int2){_inherits(Int16,_Int2);var _super142=_createSuper(Int16);function Int16(){_classCallCheck(this,Int16);return _super142.call(this,true,16);}return _createClass(Int16);}(Int);var Int32=/*#__PURE__*/function(_Int3){_inherits(Int32,_Int3);var _super143=_createSuper(Int32);function Int32(){_classCallCheck(this,Int32);return _super143.call(this,true,32);}return _createClass(Int32);}(Int);var Uint8=/*#__PURE__*/function(_Int4){_inherits(Uint8,_Int4);var _super144=_createSuper(Uint8);function Uint8(){_classCallCheck(this,Uint8);return _super144.call(this,false,8);}return _createClass(Uint8);}(Int);var Uint16=/*#__PURE__*/function(_Int5){_inherits(Uint16,_Int5);var _super145=_createSuper(Uint16);function Uint16(){_classCallCheck(this,Uint16);return _super145.call(this,false,16);}return _createClass(Uint16);}(Int);var Uint32=/*#__PURE__*/function(_Int6){_inherits(Uint32,_Int6);var _super146=_createSuper(Uint32);function Uint32(){_classCallCheck(this,Uint32);return _super146.call(this,false,32);}return _createClass(Uint32);}(Int);var Precision={HALF:16,SINGLE:32,DOUBLE:64};_Symbol$toStringTag2=Symbol.toStringTag;var Float=/*#__PURE__*/function(_DataType2,_Symbol$toStringTag4){_inherits(Float,_DataType2);var _super147=_createSuper(Float);function Float(precision){var _this118;_classCallCheck(this,Float);_this118=_super147.call(this);_defineProperty(_assertThisInitialized(_this118),"precision",void 0);_this118.precision=precision;return _this118;}_createClass(Float,[{key:"typeId",get:function get(){return Type.Float;}},{key:_Symbol$toStringTag4,get:function get(){return'Float';}},{key:"toString",value:function toString(){return"Float".concat(this.precision);}}]);return Float;}(DataType,_Symbol$toStringTag2);var Float32=/*#__PURE__*/function(_Float){_inherits(Float32,_Float);var _super148=_createSuper(Float32);function Float32(){_classCallCheck(this,Float32);return _super148.call(this,Precision.SINGLE);}return _createClass(Float32);}(Float);var Float64=/*#__PURE__*/function(_Float2){_inherits(Float64,_Float2);var _super149=_createSuper(Float64);function Float64(){_classCallCheck(this,Float64);return _super149.call(this,Precision.DOUBLE);}return _createClass(Float64);}(Float);_Symbol$toStringTag7=Symbol.toStringTag;var FixedSizeList=/*#__PURE__*/function(_DataType3,_Symbol$toStringTag5){_inherits(FixedSizeList,_DataType3);var _super150=_createSuper(FixedSizeList);function FixedSizeList(listSize,child){var _this119;_classCallCheck(this,FixedSizeList);_this119=_super150.call(this);_defineProperty(_assertThisInitialized(_this119),"listSize",void 0);_defineProperty(_assertThisInitialized(_this119),"children",void 0);_this119.listSize=listSize;_this119.children=[child];return _this119;}_createClass(FixedSizeList,[{key:"typeId",get:function get(){return Type.FixedSizeList;}},{key:"valueType",get:function get(){return this.children[0].type;}},{key:"valueField",get:function get(){return this.children[0];}},{key:_Symbol$toStringTag5,get:function get(){return'FixedSizeList';}},{key:"toString",value:function toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">");}}]);return FixedSizeList;}(DataType,_Symbol$toStringTag7);function getArrowTypeFromTypedArray(array){switch(array.constructor){case Int8Array:return new Int8();case Uint8Array:return new Uint8();case Int16Array:return new Int16();case Uint16Array:return new Uint16();case Int32Array:return new Int32();case Uint32Array:return new Uint32();case Float32Array:return new Float32();case Float64Array:return new Float64();default:throw new Error('array type not supported');}}function deduceMeshField(attributeName,attribute,optionalMetadata){var type=getArrowTypeFromTypedArray(attribute.value);var metadata=optionalMetadata?optionalMetadata:makeMeshAttributeMetadata(attribute);var field=new Field(attributeName,new FixedSizeList(attribute.size,new Field('value',type)),false,metadata);return field;}function makeMeshAttributeMetadata(attribute){var result=new Map();if('byteOffset'in attribute){result.set('byteOffset',attribute.byteOffset.toString(10));}if('byteStride'in attribute){result.set('byteStride',attribute.byteStride.toString(10));}if('normalized'in attribute){result.set('normalized',attribute.normalized.toString());}return result;}function getDracoSchema(attributes,loaderData,indices){var metadataMap=makeMetadata(loaderData.metadata);var fields=[];var namedLoaderDataAttributes=transformAttributesLoaderData(loaderData.attributes);for(var attributeName in attributes){var attribute=attributes[attributeName];var field=getArrowFieldFromAttribute(attributeName,attribute,namedLoaderDataAttributes[attributeName]);fields.push(field);}if(indices){var indicesField=getArrowFieldFromAttribute('indices',indices);fields.push(indicesField);}return new Schema(fields,metadataMap);}function transformAttributesLoaderData(loaderData){var result={};for(var key in loaderData){var dracoAttribute=loaderData[key];result[dracoAttribute.name||'undefined']=dracoAttribute;}return result;}function getArrowFieldFromAttribute(attributeName,attribute,loaderData){var metadataMap=loaderData?makeMetadata(loaderData.metadata):undefined;var field=deduceMeshField(attributeName,attribute,metadataMap);return field;}function makeMetadata(metadata){var metadataMap=new Map();for(var key in metadata){metadataMap.set("".concat(key,".string"),JSON.stringify(metadata[key]));}return metadataMap;}var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP={POSITION:'POSITION',NORMAL:'NORMAL',COLOR:'COLOR_0',TEX_COORD:'TEXCOORD_0'};var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};var INDEX_ITEM_SIZE=4;var DracoParser=/*#__PURE__*/function(){function DracoParser(draco){_classCallCheck(this,DracoParser);_defineProperty(this,"draco",void 0);_defineProperty(this,"decoder",void 0);_defineProperty(this,"metadataQuerier",void 0);this.draco=draco;this.decoder=new this.draco.Decoder();this.metadataQuerier=new this.draco.MetadataQuerier();}_createClass(DracoParser,[{key:"destroy",value:function destroy(){this.draco.destroy(this.decoder);this.draco.destroy(this.metadataQuerier);}},{key:"parseSync",value:function parseSync(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var buffer=new this.draco.DecoderBuffer();buffer.Init(new Int8Array(arrayBuffer),arrayBuffer.byteLength);this._disableAttributeTransforms(options);var geometry_type=this.decoder.GetEncodedGeometryType(buffer);var dracoGeometry=geometry_type===this.draco.TRIANGULAR_MESH?new this.draco.Mesh():new this.draco.PointCloud();try{var dracoStatus;switch(geometry_type){case this.draco.TRIANGULAR_MESH:dracoStatus=this.decoder.DecodeBufferToMesh(buffer,dracoGeometry);break;case this.draco.POINT_CLOUD:dracoStatus=this.decoder.DecodeBufferToPointCloud(buffer,dracoGeometry);break;default:throw new Error('DRACO: Unknown geometry type.');}if(!dracoStatus.ok()||!dracoGeometry.ptr){var message="DRACO decompression failed: ".concat(dracoStatus.error_msg());throw new Error(message);}var loaderData=this._getDracoLoaderData(dracoGeometry,geometry_type,options);var geometry=this._getMeshData(dracoGeometry,loaderData,options);var boundingBox=getMeshBoundingBox(geometry.attributes);var schema=getDracoSchema(geometry.attributes,loaderData,geometry.indices);var data=_objectSpread(_objectSpread({loader:'draco',loaderData:loaderData,header:{vertexCount:dracoGeometry.num_points(),boundingBox:boundingBox}},geometry),{},{schema:schema});return data;}finally{this.draco.destroy(buffer);if(dracoGeometry){this.draco.destroy(dracoGeometry);}}}},{key:"_getDracoLoaderData",value:function _getDracoLoaderData(dracoGeometry,geometry_type,options){var metadata=this._getTopLevelMetadata(dracoGeometry);var attributes=this._getDracoAttributes(dracoGeometry,options);return{geometry_type:geometry_type,num_attributes:dracoGeometry.num_attributes(),num_points:dracoGeometry.num_points(),num_faces:dracoGeometry instanceof this.draco.Mesh?dracoGeometry.num_faces():0,metadata:metadata,attributes:attributes};}},{key:"_getDracoAttributes",value:function _getDracoAttributes(dracoGeometry,options){var dracoAttributes={};for(var attributeId=0;attributeId2&&arguments[2]!==undefined?arguments[2]:false;if(!array){return null;}if(Array.isArray(array)){return new ArrayType(array);}if(convertTypedArrays&&!(array instanceof ArrayType)){return new ArrayType(array);}return array;}var KHR_DRACO_MESH_COMPRESSION='KHR_draco_mesh_compression';var name$3=KHR_DRACO_MESH_COMPRESSION;function preprocess$1(gltfData,options,context){var scenegraph=new GLTFScenegraph(gltfData);var _iterator25=_createForOfIteratorHelper(makeMeshPrimitiveIterator(scenegraph)),_step25;try{for(_iterator25.s();!(_step25=_iterator25.n()).done;){var _primitive=_step25.value;if(scenegraph.getObjectExtension(_primitive,KHR_DRACO_MESH_COMPRESSION));}}catch(err){_iterator25.e(err);}finally{_iterator25.f();}}function decode$3(_x72,_x73,_x74){return _decode$2.apply(this,arguments);}function _decode$2(){_decode$2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee40(gltfData,options,context){var _options$gltf,scenegraph,promises,_iterator48,_step48,_primitive5;return _regeneratorRuntime().wrap(function _callee40$(_context44){while(1){switch(_context44.prev=_context44.next){case 0:if(options!==null&&options!==void 0&&(_options$gltf=options.gltf)!==null&&_options$gltf!==void 0&&_options$gltf.decompressMeshes){_context44.next=2;break;}return _context44.abrupt("return");case 2:scenegraph=new GLTFScenegraph(gltfData);promises=[];_iterator48=_createForOfIteratorHelper(makeMeshPrimitiveIterator(scenegraph));try{for(_iterator48.s();!(_step48=_iterator48.n()).done;){_primitive5=_step48.value;if(scenegraph.getObjectExtension(_primitive5,KHR_DRACO_MESH_COMPRESSION)){promises.push(decompressPrimitive(scenegraph,_primitive5,options,context));}}}catch(err){_iterator48.e(err);}finally{_iterator48.f();}_context44.next=8;return Promise.all(promises);case 8:scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);case 9:case"end":return _context44.stop();}}},_callee40);}));return _decode$2.apply(this,arguments);}function encode$3(gltfData){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var scenegraph=new GLTFScenegraph(gltfData);var _iterator26=_createForOfIteratorHelper(scenegraph.json.meshes||[]),_step26;try{for(_iterator26.s();!(_step26=_iterator26.n()).done;){var _mesh3=_step26.value;compressMesh(_mesh3);scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);}}catch(err){_iterator26.e(err);}finally{_iterator26.f();}}function decompressPrimitive(_x75,_x76,_x77,_x78){return _decompressPrimitive.apply(this,arguments);}function _decompressPrimitive(){_decompressPrimitive=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee41(scenegraph,primitive,options,context){var dracoExtension,buffer,bufferCopy,parse,dracoOptions,decodedData,decodedAttributes,_i601,_Object$entries5,_Object$entries5$_i,attributeName,decodedAttribute,accessorIndex,accessor;return _regeneratorRuntime().wrap(function _callee41$(_context45){while(1){switch(_context45.prev=_context45.next){case 0:dracoExtension=scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION);if(dracoExtension){_context45.next=3;break;}return _context45.abrupt("return");case 3:buffer=scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);bufferCopy=sliceArrayBuffer(buffer.buffer,buffer.byteOffset);parse=context.parse;dracoOptions=_objectSpread({},options);delete dracoOptions['3d-tiles'];_context45.next=10;return parse(bufferCopy,DracoLoader,dracoOptions,context);case 10:decodedData=_context45.sent;decodedAttributes=getGLTFAccessors(decodedData.attributes);for(_i601=0,_Object$entries5=Object.entries(decodedAttributes);_i601<_Object$entries5.length;_i601++){_Object$entries5$_i=_slicedToArray(_Object$entries5[_i601],2),attributeName=_Object$entries5$_i[0],decodedAttribute=_Object$entries5$_i[1];if(attributeName in primitive.attributes){accessorIndex=primitive.attributes[attributeName];accessor=scenegraph.getAccessor(accessorIndex);if(accessor!==null&&accessor!==void 0&&accessor.min&&accessor!==null&&accessor!==void 0&&accessor.max){decodedAttribute.min=accessor.min;decodedAttribute.max=accessor.max;}}}primitive.attributes=decodedAttributes;if(decodedData.indices){primitive.indices=getGLTFAccessor(decodedData.indices);}checkPrimitive(primitive);case 16:case"end":return _context45.stop();}}},_callee41);}));return _decompressPrimitive.apply(this,arguments);}function compressMesh(attributes,indices){var mode=arguments.length>2&&arguments[2]!==undefined?arguments[2]:4;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _context$parseSync;if(!options.DracoWriter){throw new Error('options.gltf.DracoWriter not provided');}var compressedData=options.DracoWriter.encodeSync({attributes:attributes});var decodedData=context===null||context===void 0?void 0:(_context$parseSync=context.parseSync)===null||_context$parseSync===void 0?void 0:_context$parseSync.call(context,{attributes:attributes});var fauxAccessors=options._addFauxAttributes(decodedData.attributes);var bufferViewIndex=options.addBufferView(compressedData);var glTFMesh={primitives:[{attributes:fauxAccessors,mode:mode,extensions:_defineProperty2({},KHR_DRACO_MESH_COMPRESSION,{bufferView:bufferViewIndex,attributes:fauxAccessors})}]};return glTFMesh;}function checkPrimitive(primitive){if(!primitive.attributes&&Object.keys(primitive.attributes).length>0){throw new Error('glTF: Empty primitive detected: Draco decompression failure?');}}function makeMeshPrimitiveIterator(scenegraph){var _iterator27,_step27,_mesh4,_iterator28,_step28,_primitive2;return _regeneratorRuntime().wrap(function makeMeshPrimitiveIterator$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_iterator27=_createForOfIteratorHelper(scenegraph.json.meshes||[]);_context10.prev=1;_iterator27.s();case 3:if((_step27=_iterator27.n()).done){_context10.next=24;break;}_mesh4=_step27.value;_iterator28=_createForOfIteratorHelper(_mesh4.primitives);_context10.prev=6;_iterator28.s();case 8:if((_step28=_iterator28.n()).done){_context10.next=14;break;}_primitive2=_step28.value;_context10.next=12;return _primitive2;case 12:_context10.next=8;break;case 14:_context10.next=19;break;case 16:_context10.prev=16;_context10.t0=_context10["catch"](6);_iterator28.e(_context10.t0);case 19:_context10.prev=19;_iterator28.f();return _context10.finish(19);case 22:_context10.next=3;break;case 24:_context10.next=29;break;case 26:_context10.prev=26;_context10.t1=_context10["catch"](1);_iterator27.e(_context10.t1);case 29:_context10.prev=29;_iterator27.f();return _context10.finish(29);case 32:case"end":return _context10.stop();}}},_marked3,null,[[1,26,29,32],[6,16,19,22]]);}var KHR_draco_mesh_compression=/*#__PURE__*/Object.freeze({__proto__:null,name:name$3,preprocess:preprocess$1,decode:decode$3,encode:encode$3});var KHR_LIGHTS_PUNCTUAL='KHR_lights_punctual';var name$2=KHR_LIGHTS_PUNCTUAL;function decode$2(_x79){return _decode$3.apply(this,arguments);}function _decode$3(){_decode$3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee42(gltfData){var gltfScenegraph,json,extension,_iterator49,_step49,_node12,nodeExtension;return _regeneratorRuntime().wrap(function _callee42$(_context46){while(1){switch(_context46.prev=_context46.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;extension=gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);if(extension){gltfScenegraph.json.lights=extension.lights;gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);}_iterator49=_createForOfIteratorHelper(json.nodes||[]);try{for(_iterator49.s();!(_step49=_iterator49.n()).done;){_node12=_step49.value;nodeExtension=gltfScenegraph.getObjectExtension(_node12,KHR_LIGHTS_PUNCTUAL);if(nodeExtension){_node12.light=nodeExtension.light;}gltfScenegraph.removeObjectExtension(_node12,KHR_LIGHTS_PUNCTUAL);}}catch(err){_iterator49.e(err);}finally{_iterator49.f();}case 6:case"end":return _context46.stop();}}},_callee42);}));return _decode$3.apply(this,arguments);}function encode$2(_x80){return _encode$.apply(this,arguments);}function _encode$(){_encode$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee43(gltfData){var gltfScenegraph,json,extension,_iterator50,_step50,light,_node13;return _regeneratorRuntime().wrap(function _callee43$(_context47){while(1){switch(_context47.prev=_context47.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;if(json.lights){extension=gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);assert$1(!extension.lights);extension.lights=json.lights;delete json.lights;}if(gltfScenegraph.json.lights){_iterator50=_createForOfIteratorHelper(gltfScenegraph.json.lights);try{for(_iterator50.s();!(_step50=_iterator50.n()).done;){light=_step50.value;_node13=light.node;gltfScenegraph.addObjectExtension(_node13,KHR_LIGHTS_PUNCTUAL,light);}}catch(err){_iterator50.e(err);}finally{_iterator50.f();}delete gltfScenegraph.json.lights;}case 4:case"end":return _context47.stop();}}},_callee43);}));return _encode$.apply(this,arguments);}var KHR_lights_punctual=/*#__PURE__*/Object.freeze({__proto__:null,name:name$2,decode:decode$2,encode:encode$2});var KHR_MATERIALS_UNLIT='KHR_materials_unlit';var name$1=KHR_MATERIALS_UNLIT;function decode$1(_x81){return _decode$4.apply(this,arguments);}function _decode$4(){_decode$4=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee44(gltfData){var gltfScenegraph,json,_iterator51,_step51,material,extension;return _regeneratorRuntime().wrap(function _callee44$(_context48){while(1){switch(_context48.prev=_context48.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);_iterator51=_createForOfIteratorHelper(json.materials||[]);try{for(_iterator51.s();!(_step51=_iterator51.n()).done;){material=_step51.value;extension=material.extensions&&material.extensions.KHR_materials_unlit;if(extension){material.unlit=true;}gltfScenegraph.removeObjectExtension(material,KHR_MATERIALS_UNLIT);}}catch(err){_iterator51.e(err);}finally{_iterator51.f();}case 5:case"end":return _context48.stop();}}},_callee44);}));return _decode$4.apply(this,arguments);}function encode$1(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var json=gltfScenegraph.json;if(gltfScenegraph.materials){var _iterator29=_createForOfIteratorHelper(json.materials||[]),_step29;try{for(_iterator29.s();!(_step29=_iterator29.n()).done;){var material=_step29.value;if(material.unlit){delete material.unlit;gltfScenegraph.addObjectExtension(material,KHR_MATERIALS_UNLIT,{});gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);}}}catch(err){_iterator29.e(err);}finally{_iterator29.f();}}}var KHR_materials_unlit=/*#__PURE__*/Object.freeze({__proto__:null,name:name$1,decode:decode$1,encode:encode$1});var KHR_TECHNIQUES_WEBGL='KHR_techniques_webgl';var name=KHR_TECHNIQUES_WEBGL;function decode(_x82){return _decode.apply(this,arguments);}function _decode(){_decode=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee45(gltfData){var gltfScenegraph,json,extension,techniques,_iterator52,_step52,material,materialExtension;return _regeneratorRuntime().wrap(function _callee45$(_context49){while(1){switch(_context49.prev=_context49.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;extension=gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);if(extension){techniques=resolveTechniques(extension,gltfScenegraph);_iterator52=_createForOfIteratorHelper(json.materials||[]);try{for(_iterator52.s();!(_step52=_iterator52.n()).done;){material=_step52.value;materialExtension=gltfScenegraph.getObjectExtension(material,KHR_TECHNIQUES_WEBGL);if(materialExtension){material.technique=Object.assign({},materialExtension,techniques[materialExtension.technique]);material.technique.values=resolveValues(material.technique,gltfScenegraph);}gltfScenegraph.removeObjectExtension(material,KHR_TECHNIQUES_WEBGL);}}catch(err){_iterator52.e(err);}finally{_iterator52.f();}gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);}case 4:case"end":return _context49.stop();}}},_callee45);}));return _decode.apply(this,arguments);}function encode(_x83,_x84){return _encode.apply(this,arguments);}function _encode(){_encode=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee46(gltfData,options){return _regeneratorRuntime().wrap(function _callee46$(_context50){while(1){switch(_context50.prev=_context50.next){case 0:case"end":return _context50.stop();}}},_callee46);}));return _encode.apply(this,arguments);}function resolveTechniques(techniquesExtension,gltfScenegraph){var _techniquesExtension$=techniquesExtension.programs,programs=_techniquesExtension$===void 0?[]:_techniquesExtension$,_techniquesExtension$2=techniquesExtension.shaders,shaders=_techniquesExtension$2===void 0?[]:_techniquesExtension$2,_techniquesExtension$3=techniquesExtension.techniques,techniques=_techniquesExtension$3===void 0?[]:_techniquesExtension$3;var textDecoder=new TextDecoder();shaders.forEach(function(shader){if(Number.isFinite(shader.bufferView)){shader.code=textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));}else{throw new Error('KHR_techniques_webgl: no shader code');}});programs.forEach(function(program){program.fragmentShader=shaders[program.fragmentShader];program.vertexShader=shaders[program.vertexShader];});techniques.forEach(function(technique){technique.program=programs[technique.program];});return techniques;}function resolveValues(technique,gltfScenegraph){var values=Object.assign({},technique.values);Object.keys(technique.uniforms||{}).forEach(function(uniform){if(technique.uniforms[uniform].value&&!(uniform in values)){values[uniform]=technique.uniforms[uniform].value;}});Object.keys(values).forEach(function(uniform){if(_typeof(values[uniform])==='object'&&values[uniform].index!==undefined){values[uniform].texture=gltfScenegraph.getTexture(values[uniform].index);}});return values;}var KHR_techniques_webgl=/*#__PURE__*/Object.freeze({__proto__:null,name:name,decode:decode,encode:encode});var EXTENSIONS=[EXT_meshopt_compression,EXT_texture_webp,KHR_texture_basisu,KHR_draco_mesh_compression,KHR_lights_punctual,KHR_materials_unlit,KHR_techniques_webgl];function preprocessExtensions(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS.filter(function(extension){return useExtension(extension.name,options);});var _iterator30=_createForOfIteratorHelper(extensions),_step30;try{for(_iterator30.s();!(_step30=_iterator30.n()).done;){var extension=_step30.value;var _extension$preprocess;(_extension$preprocess=extension.preprocess)===null||_extension$preprocess===void 0?void 0:_extension$preprocess.call(extension,gltf,options,context);}}catch(err){_iterator30.e(err);}finally{_iterator30.f();}}function decodeExtensions(_x85){return _decodeExtensions.apply(this,arguments);}function _decodeExtensions(){_decodeExtensions=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee47(gltf){var options,context,extensions,_iterator53,_step53,extension,_extension$decode,_args45=arguments;return _regeneratorRuntime().wrap(function _callee47$(_context51){while(1){switch(_context51.prev=_context51.next){case 0:options=_args45.length>1&&_args45[1]!==undefined?_args45[1]:{};context=_args45.length>2?_args45[2]:undefined;extensions=EXTENSIONS.filter(function(extension){return useExtension(extension.name,options);});_iterator53=_createForOfIteratorHelper(extensions);_context51.prev=4;_iterator53.s();case 6:if((_step53=_iterator53.n()).done){_context51.next=12;break;}extension=_step53.value;_context51.next=10;return(_extension$decode=extension.decode)===null||_extension$decode===void 0?void 0:_extension$decode.call(extension,gltf,options,context);case 10:_context51.next=6;break;case 12:_context51.next=17;break;case 14:_context51.prev=14;_context51.t0=_context51["catch"](4);_iterator53.e(_context51.t0);case 17:_context51.prev=17;_iterator53.f();return _context51.finish(17);case 20:case"end":return _context51.stop();}}},_callee47,null,[[4,14,17,20]]);}));return _decodeExtensions.apply(this,arguments);}function useExtension(extensionName,options){var _options$gltf;var excludes=(options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.excludeExtensions)||{};var exclude=extensionName in excludes&&!excludes[extensionName];return!exclude;}var KHR_BINARY_GLTF='KHR_binary_glTF';function preprocess(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var json=gltfScenegraph.json;var _iterator31=_createForOfIteratorHelper(json.images||[]),_step31;try{for(_iterator31.s();!(_step31=_iterator31.n()).done;){var _image7=_step31.value;var extension=gltfScenegraph.getObjectExtension(_image7,KHR_BINARY_GLTF);if(extension){Object.assign(_image7,extension);}gltfScenegraph.removeObjectExtension(_image7,KHR_BINARY_GLTF);}}catch(err){_iterator31.e(err);}finally{_iterator31.f();}if(json.buffers&&json.buffers[0]){delete json.buffers[0].uri;}gltfScenegraph.removeExtension(KHR_BINARY_GLTF);}var GLTF_ARRAYS={accessors:'accessor',animations:'animation',buffers:'buffer',bufferViews:'bufferView',images:'image',materials:'material',meshes:'mesh',nodes:'node',samplers:'sampler',scenes:'scene',skins:'skin',textures:'texture'};var GLTF_KEYS={accessor:'accessors',animations:'animation',buffer:'buffers',bufferView:'bufferViews',image:'images',material:'materials',mesh:'meshes',node:'nodes',sampler:'samplers',scene:'scenes',skin:'skins',texture:'textures'};var GLTFV1Normalizer=/*#__PURE__*/function(){function GLTFV1Normalizer(){_classCallCheck(this,GLTFV1Normalizer);_defineProperty(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}});_defineProperty(this,"json",void 0);}_createClass(GLTFV1Normalizer,[{key:"normalize",value:function normalize(gltf,options){this.json=gltf.json;var json=gltf.json;switch(json.asset&&json.asset.version){case'2.0':return;case undefined:case'1.0':break;default:console.warn("glTF: Unknown version ".concat(json.asset.version));return;}if(!options.normalize){throw new Error('glTF v1 is not supported.');}console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');this._addAsset(json);this._convertTopLevelObjectsToArrays(json);preprocess(gltf);this._convertObjectIdsToArrayIndices(json);this._updateObjects(json);this._updateMaterial(json);}},{key:"_addAsset",value:function _addAsset(json){json.asset=json.asset||{};json.asset.version='2.0';json.asset.generator=json.asset.generator||'Normalized to glTF 2.0 by loaders.gl';}},{key:"_convertTopLevelObjectsToArrays",value:function _convertTopLevelObjectsToArrays(json){for(var arrayName in GLTF_ARRAYS){this._convertTopLevelObjectToArray(json,arrayName);}}},{key:"_convertTopLevelObjectToArray",value:function _convertTopLevelObjectToArray(json,mapName){var objectMap=json[mapName];if(!objectMap||Array.isArray(objectMap)){return;}json[mapName]=[];for(var id in objectMap){var object=objectMap[id];object.id=object.id||id;var index=json[mapName].length;json[mapName].push(object);this.idToIndexMap[mapName][id]=index;}}},{key:"_convertObjectIdsToArrayIndices",value:function _convertObjectIdsToArrayIndices(json){for(var arrayName in GLTF_ARRAYS){this._convertIdsToIndices(json,arrayName);}if('scene'in json){json.scene=this._convertIdToIndex(json.scene,'scene');}var _iterator32=_createForOfIteratorHelper(json.textures),_step32;try{for(_iterator32.s();!(_step32=_iterator32.n()).done;){var texture=_step32.value;this._convertTextureIds(texture);}}catch(err){_iterator32.e(err);}finally{_iterator32.f();}var _iterator33=_createForOfIteratorHelper(json.meshes),_step33;try{for(_iterator33.s();!(_step33=_iterator33.n()).done;){var _mesh5=_step33.value;this._convertMeshIds(_mesh5);}}catch(err){_iterator33.e(err);}finally{_iterator33.f();}var _iterator34=_createForOfIteratorHelper(json.nodes),_step34;try{for(_iterator34.s();!(_step34=_iterator34.n()).done;){var _node4=_step34.value;this._convertNodeIds(_node4);}}catch(err){_iterator34.e(err);}finally{_iterator34.f();}var _iterator35=_createForOfIteratorHelper(json.scenes),_step35;try{for(_iterator35.s();!(_step35=_iterator35.n()).done;){var _node5=_step35.value;this._convertSceneIds(_node5);}}catch(err){_iterator35.e(err);}finally{_iterator35.f();}}},{key:"_convertTextureIds",value:function _convertTextureIds(texture){if(texture.source){texture.source=this._convertIdToIndex(texture.source,'image');}}},{key:"_convertMeshIds",value:function _convertMeshIds(mesh){var _iterator36=_createForOfIteratorHelper(mesh.primitives),_step36;try{for(_iterator36.s();!(_step36=_iterator36.n()).done;){var _primitive3=_step36.value;var attributes=_primitive3.attributes,indices=_primitive3.indices,material=_primitive3.material;for(var attributeName in attributes){attributes[attributeName]=this._convertIdToIndex(attributes[attributeName],'accessor');}if(indices){_primitive3.indices=this._convertIdToIndex(indices,'accessor');}if(material){_primitive3.material=this._convertIdToIndex(material,'material');}}}catch(err){_iterator36.e(err);}finally{_iterator36.f();}}},{key:"_convertNodeIds",value:function _convertNodeIds(node){var _this122=this;if(node.children){node.children=node.children.map(function(child){return _this122._convertIdToIndex(child,'node');});}if(node.meshes){node.meshes=node.meshes.map(function(mesh){return _this122._convertIdToIndex(mesh,'mesh');});}}},{key:"_convertSceneIds",value:function _convertSceneIds(scene){var _this123=this;if(scene.nodes){scene.nodes=scene.nodes.map(function(node){return _this123._convertIdToIndex(node,'node');});}}},{key:"_convertIdsToIndices",value:function _convertIdsToIndices(json,topLevelArrayName){if(!json[topLevelArrayName]){console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));json[topLevelArrayName]=[];}var _iterator37=_createForOfIteratorHelper(json[topLevelArrayName]),_step37;try{for(_iterator37.s();!(_step37=_iterator37.n()).done;){var object=_step37.value;for(var key in object){var id=object[key];var index=this._convertIdToIndex(id,key);object[key]=index;}}}catch(err){_iterator37.e(err);}finally{_iterator37.f();}}},{key:"_convertIdToIndex",value:function _convertIdToIndex(id,key){var arrayName=GLTF_KEYS[key];if(arrayName in this.idToIndexMap){var index=this.idToIndexMap[arrayName][id];if(!Number.isFinite(index)){throw new Error("gltf v1: failed to resolve ".concat(key," with id ").concat(id));}return index;}return id;}},{key:"_updateObjects",value:function _updateObjects(json){var _iterator38=_createForOfIteratorHelper(this.json.buffers),_step38;try{for(_iterator38.s();!(_step38=_iterator38.n()).done;){var buffer=_step38.value;delete buffer.type;}}catch(err){_iterator38.e(err);}finally{_iterator38.f();}}},{key:"_updateMaterial",value:function _updateMaterial(json){var _iterator39=_createForOfIteratorHelper(json.materials),_step39;try{var _loop6=function _loop6(){var material=_step39.value;material.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var textureId=((_material$values=material.values)===null||_material$values===void 0?void 0:_material$values.tex)||((_material$values2=material.values)===null||_material$values2===void 0?void 0:_material$values2.texture2d_0);var textureIndex=json.textures.findIndex(function(texture){return texture.id===textureId;});if(textureIndex!==-1){material.pbrMetallicRoughness.baseColorTexture={index:textureIndex};}};for(_iterator39.s();!(_step39=_iterator39.n()).done;){var _material$values,_material$values2;_loop6();}}catch(err){_iterator39.e(err);}finally{_iterator39.f();}}}]);return GLTFV1Normalizer;}();function normalizeGLTFV1(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return new GLTFV1Normalizer().normalize(gltf,options);}var COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var BYTES={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var GL_SAMPLER={TEXTURE_MAG_FILTER:0x2800,TEXTURE_MIN_FILTER:0x2801,TEXTURE_WRAP_S:0x2802,TEXTURE_WRAP_T:0x2803,REPEAT:0x2901,LINEAR:0x2601,NEAREST_MIPMAP_LINEAR:0x2702};var SAMPLER_PARAMETER_GLTF_TO_GL={magFilter:GL_SAMPLER.TEXTURE_MAG_FILTER,minFilter:GL_SAMPLER.TEXTURE_MIN_FILTER,wrapS:GL_SAMPLER.TEXTURE_WRAP_S,wrapT:GL_SAMPLER.TEXTURE_WRAP_T};var DEFAULT_SAMPLER=(_DEFAULT_SAMPLER={},_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_MAG_FILTER,GL_SAMPLER.LINEAR),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_MIN_FILTER,GL_SAMPLER.NEAREST_MIPMAP_LINEAR),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_WRAP_S,GL_SAMPLER.REPEAT),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_WRAP_T,GL_SAMPLER.REPEAT),_DEFAULT_SAMPLER);function getBytesFromComponentType(componentType){return BYTES[componentType];}function getSizeFromAccessorType(type){return COMPONENTS[type];}var GLTFPostProcessor=/*#__PURE__*/function(){function GLTFPostProcessor(){_classCallCheck(this,GLTFPostProcessor);_defineProperty(this,"baseUri",'');_defineProperty(this,"json",{});_defineProperty(this,"buffers",[]);_defineProperty(this,"images",[]);}_createClass(GLTFPostProcessor,[{key:"postProcess",value:function postProcess(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var json=gltf.json,_gltf$buffers=gltf.buffers,buffers=_gltf$buffers===void 0?[]:_gltf$buffers,_gltf$images=gltf.images,images=_gltf$images===void 0?[]:_gltf$images,_gltf$baseUri=gltf.baseUri,baseUri=_gltf$baseUri===void 0?'':_gltf$baseUri;assert$1(json);this.baseUri=baseUri;this.json=json;this.buffers=buffers;this.images=images;this._resolveTree(this.json,options);return this.json;}},{key:"_resolveTree",value:function _resolveTree(json){var _this124=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(json.bufferViews){json.bufferViews=json.bufferViews.map(function(bufView,i){return _this124._resolveBufferView(bufView,i);});}if(json.images){json.images=json.images.map(function(image,i){return _this124._resolveImage(image,i);});}if(json.samplers){json.samplers=json.samplers.map(function(sampler,i){return _this124._resolveSampler(sampler,i);});}if(json.textures){json.textures=json.textures.map(function(texture,i){return _this124._resolveTexture(texture,i);});}if(json.accessors){json.accessors=json.accessors.map(function(accessor,i){return _this124._resolveAccessor(accessor,i);});}if(json.materials){json.materials=json.materials.map(function(material,i){return _this124._resolveMaterial(material,i);});}if(json.meshes){json.meshes=json.meshes.map(function(mesh,i){return _this124._resolveMesh(mesh,i);});}if(json.nodes){json.nodes=json.nodes.map(function(node,i){return _this124._resolveNode(node,i);});}if(json.skins){json.skins=json.skins.map(function(skin,i){return _this124._resolveSkin(skin,i);});}if(json.scenes){json.scenes=json.scenes.map(function(scene,i){return _this124._resolveScene(scene,i);});}if(json.scene!==undefined){json.scene=json.scenes[this.json.scene];}}},{key:"getScene",value:function getScene(index){return this._get('scenes',index);}},{key:"getNode",value:function getNode(index){return this._get('nodes',index);}},{key:"getSkin",value:function getSkin(index){return this._get('skins',index);}},{key:"getMesh",value:function getMesh(index){return this._get('meshes',index);}},{key:"getMaterial",value:function getMaterial(index){return this._get('materials',index);}},{key:"getAccessor",value:function getAccessor(index){return this._get('accessors',index);}},{key:"getCamera",value:function getCamera(index){return null;}},{key:"getTexture",value:function getTexture(index){return this._get('textures',index);}},{key:"getSampler",value:function getSampler(index){return this._get('samplers',index);}},{key:"getImage",value:function getImage(index){return this._get('images',index);}},{key:"getBufferView",value:function getBufferView(index){return this._get('bufferViews',index);}},{key:"getBuffer",value:function getBuffer(index){return this._get('buffers',index);}},{key:"_get",value:function _get(array,index){if(_typeof(index)==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){console.warn("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}},{key:"_resolveScene",value:function _resolveScene(scene,index){var _this125=this;scene.id=scene.id||"scene-".concat(index);scene.nodes=(scene.nodes||[]).map(function(node){return _this125.getNode(node);});return scene;}},{key:"_resolveNode",value:function _resolveNode(node,index){var _this126=this;node.id=node.id||"node-".concat(index);if(node.children){node.children=node.children.map(function(child){return _this126.getNode(child);});}if(node.mesh!==undefined){node.mesh=this.getMesh(node.mesh);}else if(node.meshes!==undefined&&node.meshes.length){node.mesh=node.meshes.reduce(function(accum,meshIndex){var mesh=_this126.getMesh(meshIndex);accum.id=mesh.id;accum.primitives=accum.primitives.concat(mesh.primitives);return accum;},{primitives:[]});}if(node.camera!==undefined){node.camera=this.getCamera(node.camera);}if(node.skin!==undefined){node.skin=this.getSkin(node.skin);}return node;}},{key:"_resolveSkin",value:function _resolveSkin(skin,index){skin.id=skin.id||"skin-".concat(index);skin.inverseBindMatrices=this.getAccessor(skin.inverseBindMatrices);return skin;}},{key:"_resolveMesh",value:function _resolveMesh(mesh,index){var _this127=this;mesh.id=mesh.id||"mesh-".concat(index);if(mesh.primitives){mesh.primitives=mesh.primitives.map(function(primitive){primitive=_objectSpread({},primitive);var attributes=primitive.attributes;primitive.attributes={};for(var attribute in attributes){primitive.attributes[attribute]=_this127.getAccessor(attributes[attribute]);}if(primitive.indices!==undefined){primitive.indices=_this127.getAccessor(primitive.indices);}if(primitive.material!==undefined){primitive.material=_this127.getMaterial(primitive.material);}return primitive;});}return mesh;}},{key:"_resolveMaterial",value:function _resolveMaterial(material,index){material.id=material.id||"material-".concat(index);if(material.normalTexture){material.normalTexture=_objectSpread({},material.normalTexture);material.normalTexture.texture=this.getTexture(material.normalTexture.index);}if(material.occlusionTexture){material.occlustionTexture=_objectSpread({},material.occlustionTexture);material.occlusionTexture.texture=this.getTexture(material.occlusionTexture.index);}if(material.emissiveTexture){material.emmisiveTexture=_objectSpread({},material.emmisiveTexture);material.emissiveTexture.texture=this.getTexture(material.emissiveTexture.index);}if(!material.emissiveFactor){material.emissiveFactor=material.emmisiveTexture?[1,1,1]:[0,0,0];}if(material.pbrMetallicRoughness){material.pbrMetallicRoughness=_objectSpread({},material.pbrMetallicRoughness);var mr=material.pbrMetallicRoughness;if(mr.baseColorTexture){mr.baseColorTexture=_objectSpread({},mr.baseColorTexture);mr.baseColorTexture.texture=this.getTexture(mr.baseColorTexture.index);}if(mr.metallicRoughnessTexture){mr.metallicRoughnessTexture=_objectSpread({},mr.metallicRoughnessTexture);mr.metallicRoughnessTexture.texture=this.getTexture(mr.metallicRoughnessTexture.index);}}return material;}},{key:"_resolveAccessor",value:function _resolveAccessor(accessor,index){accessor.id=accessor.id||"accessor-".concat(index);if(accessor.bufferView!==undefined){accessor.bufferView=this.getBufferView(accessor.bufferView);}accessor.bytesPerComponent=getBytesFromComponentType(accessor.componentType);accessor.components=getSizeFromAccessorType(accessor.type);accessor.bytesPerElement=accessor.bytesPerComponent*accessor.components;if(accessor.bufferView){var buffer=accessor.bufferView.buffer;var _getAccessorArrayType2=getAccessorArrayTypeAndLength(accessor,accessor.bufferView),ArrayType=_getAccessorArrayType2.ArrayType,byteLength=_getAccessorArrayType2.byteLength;var byteOffset=(accessor.bufferView.byteOffset||0)+(accessor.byteOffset||0)+buffer.byteOffset;var cutBuffer=buffer.arrayBuffer.slice(byteOffset,byteOffset+byteLength);if(accessor.bufferView.byteStride){cutBuffer=this._getValueFromInterleavedBuffer(buffer,byteOffset,accessor.bufferView.byteStride,accessor.bytesPerElement,accessor.count);}accessor.value=new ArrayType(cutBuffer);}return accessor;}},{key:"_getValueFromInterleavedBuffer",value:function _getValueFromInterleavedBuffer(buffer,byteOffset,byteStride,bytesPerElement,count){var result=new Uint8Array(count*bytesPerElement);for(var _i508=0;_i5081&&arguments[1]!==undefined?arguments[1]:0;return"".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}function isGLB(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var dataView=new DataView(arrayBuffer);var _options$magic=options.magic,magic=_options$magic===void 0?MAGIC_glTF:_options$magic;var magic1=dataView.getUint32(byteOffset,false);return magic1===magic||magic1===MAGIC_glTF;}function parseGLBSync(glb,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var dataView=new DataView(arrayBuffer);var type=getMagicString(dataView,byteOffset+0);var version=dataView.getUint32(byteOffset+4,LE);var byteLength=dataView.getUint32(byteOffset+8,LE);Object.assign(glb,{header:{byteOffset:byteOffset,byteLength:byteLength,hasBinChunk:false},type:type,version:version,json:{},binChunks:[]});byteOffset+=GLB_FILE_HEADER_SIZE;switch(glb.version){case 1:return parseGLBV1(glb,dataView,byteOffset);case 2:return parseGLBV2(glb,dataView,byteOffset,options={});default:throw new Error("Invalid GLB version ".concat(glb.version,". Only supports v1 and v2."));}}function parseGLBV1(glb,dataView,byteOffset){assert$5(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);var contentLength=dataView.getUint32(byteOffset+0,LE);var contentFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;assert$5(contentFormat===GLB_V1_CONTENT_FORMAT_JSON);parseJSONChunk(glb,dataView,byteOffset,contentLength);byteOffset+=contentLength;byteOffset+=parseBINChunk(glb,dataView,byteOffset,glb.header.byteLength);return byteOffset;}function parseGLBV2(glb,dataView,byteOffset,options){assert$5(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);parseGLBChunksSync(glb,dataView,byteOffset,options);return byteOffset+glb.header.byteLength;}function parseGLBChunksSync(glb,dataView,byteOffset,options){while(byteOffset+8<=glb.header.byteLength){var chunkLength=dataView.getUint32(byteOffset+0,LE);var chunkFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;switch(chunkFormat){case GLB_CHUNK_TYPE_JSON:parseJSONChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_BIN:parseBINChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:if(!options.strict){parseJSONChunk(glb,dataView,byteOffset,chunkLength);}break;case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:if(!options.strict){parseBINChunk(glb,dataView,byteOffset,chunkLength);}break;}byteOffset+=padToNBytes(chunkLength,4);}return byteOffset;}function parseJSONChunk(glb,dataView,byteOffset,chunkLength){var jsonChunk=new Uint8Array(dataView.buffer,byteOffset,chunkLength);var textDecoder=new TextDecoder('utf8');var jsonText=textDecoder.decode(jsonChunk);glb.json=JSON.parse(jsonText);return padToNBytes(chunkLength,4);}function parseBINChunk(glb,dataView,byteOffset,chunkLength){glb.header.hasBinChunk=true;glb.binChunks.push({byteOffset:byteOffset,byteLength:chunkLength,arrayBuffer:dataView.buffer});return padToNBytes(chunkLength,4);}function parseGLTF$1(_x86,_x87){return _parseGLTF$.apply(this,arguments);}function _parseGLTF$(){_parseGLTF$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee48(gltf,arrayBufferOrString){var byteOffset,options,context,_options$gltf,_options$gltf2,_options$gltf3,_options$gltf4,promises,_promise,promise,_args46=arguments;return _regeneratorRuntime().wrap(function _callee48$(_context52){while(1){switch(_context52.prev=_context52.next){case 0:byteOffset=_args46.length>2&&_args46[2]!==undefined?_args46[2]:0;options=_args46.length>3?_args46[3]:undefined;context=_args46.length>4?_args46[4]:undefined;parseGLTFContainerSync(gltf,arrayBufferOrString,byteOffset,options);normalizeGLTFV1(gltf,{normalize:options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.normalize});preprocessExtensions(gltf,options,context);promises=[];if(!(options!==null&&options!==void 0&&(_options$gltf2=options.gltf)!==null&&_options$gltf2!==void 0&&_options$gltf2.loadBuffers&&gltf.json.buffers)){_context52.next=10;break;}_context52.next=10;return loadBuffers(gltf,options,context);case 10:if(options!==null&&options!==void 0&&(_options$gltf3=options.gltf)!==null&&_options$gltf3!==void 0&&_options$gltf3.loadImages){_promise=loadImages(gltf,options,context);promises.push(_promise);}promise=decodeExtensions(gltf,options,context);promises.push(promise);_context52.next=15;return Promise.all(promises);case 15:return _context52.abrupt("return",options!==null&&options!==void 0&&(_options$gltf4=options.gltf)!==null&&_options$gltf4!==void 0&&_options$gltf4.postProcess?postProcessGLTF(gltf,options):gltf);case 16:case"end":return _context52.stop();}}},_callee48);}));return _parseGLTF$.apply(this,arguments);}function parseGLTFContainerSync(gltf,data,byteOffset,options){if(options.uri){gltf.baseUri=options.uri;}if(data instanceof ArrayBuffer&&!isGLB(data,byteOffset,options)){var textDecoder=new TextDecoder();data=textDecoder.decode(data);}if(typeof data==='string'){gltf.json=parseJSON(data);}else if(data instanceof ArrayBuffer){var glb={};byteOffset=parseGLBSync(glb,data,byteOffset,options.glb);assert$1(glb.type==='glTF',"Invalid GLB magic string ".concat(glb.type));gltf._glb=glb;gltf.json=glb.json;}else{assert$1(false,'GLTF: must be ArrayBuffer or string');}var buffers=gltf.json.buffers||[];gltf.buffers=new Array(buffers.length).fill(null);if(gltf._glb&&gltf._glb.header.hasBinChunk){var binChunks=gltf._glb.binChunks;gltf.buffers[0]={arrayBuffer:binChunks[0].arrayBuffer,byteOffset:binChunks[0].byteOffset,byteLength:binChunks[0].byteLength};}var images=gltf.json.images||[];gltf.images=new Array(images.length).fill({});}function loadBuffers(_x88,_x89,_x90){return _loadBuffers.apply(this,arguments);}function _loadBuffers(){_loadBuffers=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee49(gltf,options,context){var buffers,_i602,buffer,_context$fetch,_response$arrayBuffer,_fetch,uri,response,arrayBuffer;return _regeneratorRuntime().wrap(function _callee49$(_context53){while(1){switch(_context53.prev=_context53.next){case 0:buffers=gltf.json.buffers||[];_i602=0;case 2:if(!(_i6021&&arguments[1]!==undefined?arguments[1]:true;var transfers=arguments.length>2?arguments[2]:undefined;var transfersSet=transfers||new Set();if(!object);else if(isTransferable(object)){transfersSet.add(object);}else if(isTransferable(object.buffer)){transfersSet.add(object.buffer);}else if(ArrayBuffer.isView(object));else if(recursive&&_typeof(object)==='object'){for(var key in object){getTransferList(object[key],recursive,transfersSet);}}return transfers===undefined?Array.from(transfersSet):[];}function isTransferable(object){if(!object){return false;}if(object instanceof ArrayBuffer){return true;}if(typeof MessagePort!=='undefined'&&object instanceof MessagePort){return true;}if(typeof ImageBitmap!=='undefined'&&object instanceof ImageBitmap){return true;}if(typeof OffscreenCanvas!=='undefined'&&object instanceof OffscreenCanvas){return true;}return false;}var NOOP=function NOOP(){};var WorkerThread=/*#__PURE__*/function(){function WorkerThread(props){_classCallCheck(this,WorkerThread);_defineProperty(this,"name",void 0);_defineProperty(this,"source",void 0);_defineProperty(this,"url",void 0);_defineProperty(this,"terminated",false);_defineProperty(this,"worker",void 0);_defineProperty(this,"onMessage",void 0);_defineProperty(this,"onError",void 0);_defineProperty(this,"_loadableURL",'');var name=props.name,source=props.source,url=props.url;assert$4(source||url);this.name=name;this.source=source;this.url=url;this.onMessage=NOOP;this.onError=function(error){return console.log(error);};this.worker=isBrowser$3?this._createBrowserWorker():this._createNodeWorker();}_createClass(WorkerThread,[{key:"destroy",value:function destroy(){this.onMessage=NOOP;this.onError=NOOP;this.worker.terminate();this.terminated=true;}},{key:"isRunning",get:function get(){return Boolean(this.onMessage);}},{key:"postMessage",value:function postMessage(data,transferList){transferList=transferList||getTransferList(data);this.worker.postMessage(data,transferList);}},{key:"_getErrorFromErrorEvent",value:function _getErrorFromErrorEvent(event){var message='Failed to load ';message+="worker ".concat(this.name," from ").concat(this.url,". ");if(event.message){message+="".concat(event.message," in ");}if(event.lineno){message+=":".concat(event.lineno,":").concat(event.colno);}return new Error(message);}},{key:"_createBrowserWorker",value:function _createBrowserWorker(){var _this113=this;this._loadableURL=getLoadableWorkerURL({source:this.source,url:this.url});var worker=new Worker(this._loadableURL,{name:this.name});worker.onmessage=function(event){if(!event.data){_this113.onError(new Error('No data received'));}else{_this113.onMessage(event.data);}};worker.onerror=function(error){_this113.onError(_this113._getErrorFromErrorEvent(error));_this113.terminated=true;};worker.onmessageerror=function(event){return console.error(event);};return worker;}},{key:"_createNodeWorker",value:function _createNodeWorker(){var _this114=this;var worker;if(this.url){var absolute=this.url.includes(':/')||this.url.startsWith('/');var url=absolute?this.url:"./".concat(this.url);worker=new Worker$1(url,{eval:false});}else if(this.source){worker=new Worker$1(this.source,{eval:true});}else{throw new Error('no worker');}worker.on('message',function(data){_this114.onMessage(data);});worker.on('error',function(error){_this114.onError(error);});worker.on('exit',function(code){});return worker;}}],[{key:"isSupported",value:function isSupported(){return typeof Worker!=='undefined'&&isBrowser$3||_typeof(Worker$1)!==undefined;}}]);return WorkerThread;}();var WorkerPool=/*#__PURE__*/function(){function WorkerPool(props){_classCallCheck(this,WorkerPool);_defineProperty(this,"name",'unnamed');_defineProperty(this,"source",void 0);_defineProperty(this,"url",void 0);_defineProperty(this,"maxConcurrency",1);_defineProperty(this,"maxMobileConcurrency",1);_defineProperty(this,"onDebug",function(){});_defineProperty(this,"reuseWorkers",true);_defineProperty(this,"props",{});_defineProperty(this,"jobQueue",[]);_defineProperty(this,"idleQueue",[]);_defineProperty(this,"count",0);_defineProperty(this,"isDestroyed",false);this.source=props.source;this.url=props.url;this.setProps(props);}_createClass(WorkerPool,[{key:"destroy",value:function destroy(){this.idleQueue.forEach(function(worker){return worker.destroy();});this.isDestroyed=true;}},{key:"setProps",value:function setProps(props){this.props=_objectSpread(_objectSpread({},this.props),props);if(props.name!==undefined){this.name=props.name;}if(props.maxConcurrency!==undefined){this.maxConcurrency=props.maxConcurrency;}if(props.maxMobileConcurrency!==undefined){this.maxMobileConcurrency=props.maxMobileConcurrency;}if(props.reuseWorkers!==undefined){this.reuseWorkers=props.reuseWorkers;}if(props.onDebug!==undefined){this.onDebug=props.onDebug;}}},{key:"startJob",value:function(){var _startJob=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(name){var _this115=this;var onMessage,onError,startPromise,_args2=arguments;return _regeneratorRuntime().wrap(function _callee2$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:onMessage=_args2.length>1&&_args2[1]!==undefined?_args2[1]:function(job,type,data){return job.done(data);};onError=_args2.length>2&&_args2[2]!==undefined?_args2[2]:function(job,error){return job.error(error);};startPromise=new Promise(function(onStart){_this115.jobQueue.push({name:name,onMessage:onMessage,onError:onError,onStart:onStart});return _this115;});this._startQueuedJob();_context3.next=6;return startPromise;case 6:return _context3.abrupt("return",_context3.sent);case 7:case"end":return _context3.stop();}}},_callee2,this);}));function startJob(_x7){return _startJob.apply(this,arguments);}return startJob;}()},{key:"_startQueuedJob",value:function(){var _startQueuedJob2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(){var workerThread,queuedJob,job;return _regeneratorRuntime().wrap(function _callee3$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:if(this.jobQueue.length){_context4.next=2;break;}return _context4.abrupt("return");case 2:workerThread=this._getAvailableWorker();if(workerThread){_context4.next=5;break;}return _context4.abrupt("return");case 5:queuedJob=this.jobQueue.shift();if(!queuedJob){_context4.next=18;break;}this.onDebug({message:'Starting job',name:queuedJob.name,workerThread:workerThread,backlog:this.jobQueue.length});job=new WorkerJob(queuedJob.name,workerThread);workerThread.onMessage=function(data){return queuedJob.onMessage(job,data.type,data.payload);};workerThread.onError=function(error){return queuedJob.onError(job,error);};queuedJob.onStart(job);_context4.prev=12;_context4.next=15;return job.result;case 15:_context4.prev=15;this.returnWorkerToQueue(workerThread);return _context4.finish(15);case 18:case"end":return _context4.stop();}}},_callee3,this,[[12,,15,18]]);}));function _startQueuedJob(){return _startQueuedJob2.apply(this,arguments);}return _startQueuedJob;}()},{key:"returnWorkerToQueue",value:function returnWorkerToQueue(worker){var shouldDestroyWorker=this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency();if(shouldDestroyWorker){worker.destroy();this.count--;}else{this.idleQueue.push(worker);}if(!this.isDestroyed){this._startQueuedJob();}}},{key:"_getAvailableWorker",value:function _getAvailableWorker(){if(this.idleQueue.length>0){return this.idleQueue.shift()||null;}if(this.count0&&arguments[0]!==undefined?arguments[0]:{};WorkerFarm._workerFarm=WorkerFarm._workerFarm||new WorkerFarm({});WorkerFarm._workerFarm.setProps(props);return WorkerFarm._workerFarm;}}]);return WorkerFarm;}();_defineProperty(WorkerFarm,"_workerFarm",void 0);var NPM_TAG='latest';function getWorkerURL(worker){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var workerOptions=options[worker.id]||{};var workerFile="".concat(worker.id,"-worker.js");var url=workerOptions.workerUrl;if(!url&&worker.id==='compression'){url=options.workerUrl;}if(options._workerType==='test'){url="modules/".concat(worker.module,"/dist/").concat(workerFile);}if(!url){var version=worker.version;if(version==='latest'){version=NPM_TAG;}var versionTag=version?"@".concat(version):'';url="https://unpkg.com/@loaders.gl/".concat(worker.module).concat(versionTag,"/dist/").concat(workerFile);}assert$4(url);return url;}function validateWorkerVersion(worker){var coreVersion=arguments.length>1&&arguments[1]!==undefined?arguments[1]:VERSION$9;assert$4(worker,'no worker provided');var workerVersion=worker.version;if(!coreVersion||!workerVersion){return false;}return true;}var ChildProcessProxy={};var node=/*#__PURE__*/Object.freeze({__proto__:null,'default':ChildProcessProxy});var VERSION$8="3.2.6";var loadLibraryPromises={};function loadLibrary(_x8){return _loadLibrary.apply(this,arguments);}function _loadLibrary(){_loadLibrary=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(libraryUrl){var moduleName,options,_args4=arguments;return _regeneratorRuntime().wrap(function _callee7$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:moduleName=_args4.length>1&&_args4[1]!==undefined?_args4[1]:null;options=_args4.length>2&&_args4[2]!==undefined?_args4[2]:{};if(moduleName){libraryUrl=getLibraryUrl(libraryUrl,moduleName,options);}loadLibraryPromises[libraryUrl]=loadLibraryPromises[libraryUrl]||loadLibraryFromFile(libraryUrl);_context11.next=6;return loadLibraryPromises[libraryUrl];case 6:return _context11.abrupt("return",_context11.sent);case 7:case"end":return _context11.stop();}}},_callee7);}));return _loadLibrary.apply(this,arguments);}function getLibraryUrl(library,moduleName,options){if(library.startsWith('http')){return library;}var modules=options.modules||{};if(modules[library]){return modules[library];}if(!isBrowser$3){return"modules/".concat(moduleName,"/dist/libs/").concat(library);}if(options.CDN){assert$4(options.CDN.startsWith('http'));return"".concat(options.CDN,"/").concat(moduleName,"@").concat(VERSION$8,"/dist/libs/").concat(library);}if(isWorker){return"../src/libs/".concat(library);}return"modules/".concat(moduleName,"/src/libs/").concat(library);}function loadLibraryFromFile(_x9){return _loadLibraryFromFile.apply(this,arguments);}function _loadLibraryFromFile(){_loadLibraryFromFile=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(libraryUrl){var _response,response,scriptSource;return _regeneratorRuntime().wrap(function _callee8$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:if(!libraryUrl.endsWith('wasm')){_context12.next=7;break;}_context12.next=3;return fetch(libraryUrl);case 3:_response=_context12.sent;_context12.next=6;return _response.arrayBuffer();case 6:return _context12.abrupt("return",_context12.sent);case 7:if(isBrowser$3){_context12.next=20;break;}_context12.prev=8;_context12.t0=node&&undefined;if(!_context12.t0){_context12.next=14;break;}_context12.next=13;return undefined(libraryUrl);case 13:_context12.t0=_context12.sent;case 14:return _context12.abrupt("return",_context12.t0);case 17:_context12.prev=17;_context12.t1=_context12["catch"](8);return _context12.abrupt("return",null);case 20:if(!isWorker){_context12.next=22;break;}return _context12.abrupt("return",importScripts(libraryUrl));case 22:_context12.next=24;return fetch(libraryUrl);case 24:response=_context12.sent;_context12.next=27;return response.text();case 27:scriptSource=_context12.sent;return _context12.abrupt("return",loadLibraryFromString(scriptSource,libraryUrl));case 29:case"end":return _context12.stop();}}},_callee8,null,[[8,17]]);}));return _loadLibraryFromFile.apply(this,arguments);}function loadLibraryFromString(scriptSource,id){if(!isBrowser$3){return undefined&&undefined(scriptSource,id);}if(isWorker){eval.call(global_,scriptSource);return null;}var script=document.createElement('script');script.id=id;try{script.appendChild(document.createTextNode(scriptSource));}catch(e){script.text=scriptSource;}document.body.appendChild(script);return null;}function canParseWithWorker(loader,options){if(!WorkerFarm.isSupported()){return false;}if(!isBrowser$3&&!(options!==null&&options!==void 0&&options._nodeWorkers)){return false;}return loader.worker&&(options===null||options===void 0?void 0:options.worker);}function parseWithWorker(_x10,_x11,_x12,_x13,_x14){return _parseWithWorker.apply(this,arguments);}function _parseWithWorker(){_parseWithWorker=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee9(loader,data,options,context,parseOnMainThread){var name,url,workerFarm,workerPool,job,result;return _regeneratorRuntime().wrap(function _callee9$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:name=loader.id;url=getWorkerURL(loader,options);workerFarm=WorkerFarm.getWorkerFarm(options);workerPool=workerFarm.getWorkerPool({name:name,url:url});options=JSON.parse(JSON.stringify(options));context=JSON.parse(JSON.stringify(context||{}));_context13.next=8;return workerPool.startJob('process-on-worker',onMessage.bind(null,parseOnMainThread));case 8:job=_context13.sent;job.postMessage('process',{input:data,options:options,context:context});_context13.next=12;return job.result;case 12:result=_context13.sent;_context13.next=15;return result.result;case 15:return _context13.abrupt("return",_context13.sent);case 16:case"end":return _context13.stop();}}},_callee9);}));return _parseWithWorker.apply(this,arguments);}function onMessage(_x15,_x16,_x17,_x18){return _onMessage2.apply(this,arguments);}function _onMessage2(){_onMessage2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee10(parseOnMainThread,job,type,payload){var id,input,options,result,message;return _regeneratorRuntime().wrap(function _callee10$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:_context14.t0=type;_context14.next=_context14.t0==='done'?3:_context14.t0==='error'?5:_context14.t0==='process'?7:20;break;case 3:job.done(payload);return _context14.abrupt("break",21);case 5:job.error(new Error(payload.error));return _context14.abrupt("break",21);case 7:id=payload.id,input=payload.input,options=payload.options;_context14.prev=8;_context14.next=11;return parseOnMainThread(input,options);case 11:result=_context14.sent;job.postMessage('done',{id:id,result:result});_context14.next=19;break;case 15:_context14.prev=15;_context14.t1=_context14["catch"](8);message=_context14.t1 instanceof Error?_context14.t1.message:'unknown error';job.postMessage('error',{id:id,error:message});case 19:return _context14.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(type));case 21:case"end":return _context14.stop();}}},_callee10,null,[[8,15]]);}));return _onMessage2.apply(this,arguments);}function getFirstCharacters$1(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$2(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$2(data,byteOffset,length);}return'';}function getMagicString$2(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength<=byteOffset+length){return'';}var dataView=new DataView(arrayBuffer);var magic='';for(var _i496=0;_i496=0);assert$5(padding>0);return byteLength+(padding-1)&~(padding-1);}function copyToArray(source,target,targetOffset){var sourceArray;if(source instanceof ArrayBuffer){sourceArray=new Uint8Array(source);}else{var srcByteOffset=source.byteOffset;var srcByteLength=source.byteLength;sourceArray=new Uint8Array(source.buffer||source.arrayBuffer,srcByteOffset,srcByteLength);}target.set(sourceArray,targetOffset);return targetOffset+padToNBytes(sourceArray.byteLength,4);}function concatenateArrayBuffersAsync(_x19){return _concatenateArrayBuffersAsync.apply(this,arguments);}function _concatenateArrayBuffersAsync(){_concatenateArrayBuffersAsync=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee11(asyncIterator){var arrayBuffers,_iteratorAbruptCompletion,_didIteratorError,_iteratorError,_iterator,_step,chunk;return _regeneratorRuntime().wrap(function _callee11$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:arrayBuffers=[];_iteratorAbruptCompletion=false;_didIteratorError=false;_context15.prev=3;_iterator=_asyncIterator(asyncIterator);case 5:_context15.next=7;return _iterator.next();case 7:if(!(_iteratorAbruptCompletion=!(_step=_context15.sent).done)){_context15.next=13;break;}chunk=_step.value;arrayBuffers.push(chunk);case 10:_iteratorAbruptCompletion=false;_context15.next=5;break;case 13:_context15.next=19;break;case 15:_context15.prev=15;_context15.t0=_context15["catch"](3);_didIteratorError=true;_iteratorError=_context15.t0;case 19:_context15.prev=19;_context15.prev=20;if(!(_iteratorAbruptCompletion&&_iterator["return"]!=null)){_context15.next=24;break;}_context15.next=24;return _iterator["return"]();case 24:_context15.prev=24;if(!_didIteratorError){_context15.next=27;break;}throw _iteratorError;case 27:return _context15.finish(24);case 28:return _context15.finish(19);case 29:return _context15.abrupt("return",concatenateArrayBuffers.apply(void 0,arrayBuffers));case 30:case"end":return _context15.stop();}}},_callee11,null,[[3,15,19,29],[20,,24,28]]);}));return _concatenateArrayBuffersAsync.apply(this,arguments);}var pathPrefix='';var fileAliases={};function resolvePath(filename){for(var alias in fileAliases){if(filename.startsWith(alias)){var replacement=fileAliases[alias];filename=filename.replace(alias,replacement);}}if(!filename.startsWith('http://')&&!filename.startsWith('https://')){filename="".concat(pathPrefix).concat(filename);}return filename;}function filename(url){var slashIndex=url&&url.lastIndexOf('/');return slashIndex>=0?url.substr(slashIndex+1):'';}var isBoolean=function isBoolean(x){return typeof x==='boolean';};var isFunction=function isFunction(x){return typeof x==='function';};var isObject=function isObject(x){return x!==null&&_typeof(x)==='object';};var isPureObject=function isPureObject(x){return isObject(x)&&x.constructor==={}.constructor;};var isIterable=function isIterable(x){return x&&typeof x[Symbol.iterator]==='function';};var isAsyncIterable=function isAsyncIterable(x){return x&&typeof x[Symbol.asyncIterator]==='function';};var isResponse=function isResponse(x){return typeof Response!=='undefined'&&x instanceof Response||x&&x.arrayBuffer&&x.text&&x.json;};var isBlob=function isBlob(x){return typeof Blob!=='undefined'&&x instanceof Blob;};var isBuffer=function isBuffer(x){return x&&_typeof(x)==='object'&&x.isBuffer;};var isReadableDOMStream=function isReadableDOMStream(x){return typeof ReadableStream!=='undefined'&&x instanceof ReadableStream||isObject(x)&&isFunction(x.tee)&&isFunction(x.cancel)&&isFunction(x.getReader);};var isReadableNodeStream=function isReadableNodeStream(x){return isObject(x)&&isFunction(x.read)&&isFunction(x.pipe)&&isBoolean(x.readable);};var isReadableStream=function isReadableStream(x){return isReadableDOMStream(x)||isReadableNodeStream(x);};var DATA_URL_PATTERN=/^data:([-\w.]+\/[-\w.+]+)(;|,)/;var MIME_TYPE_PATTERN=/^([-\w.]+\/[-\w.+]+)/;function parseMIMEType(mimeString){var matches=MIME_TYPE_PATTERN.exec(mimeString);if(matches){return matches[1];}return mimeString;}function parseMIMETypeFromURL(url){var matches=DATA_URL_PATTERN.exec(url);if(matches){return matches[1];}return'';}var QUERY_STRING_PATTERN=/\?.*/;function getResourceUrlAndType(resource){if(isResponse(resource)){var url=stripQueryString(resource.url||'');var contentTypeHeader=resource.headers.get('content-type')||'';return{url:url,type:parseMIMEType(contentTypeHeader)||parseMIMETypeFromURL(url)};}if(isBlob(resource)){return{url:stripQueryString(resource.name||''),type:resource.type||''};}if(typeof resource==='string'){return{url:stripQueryString(resource),type:parseMIMETypeFromURL(resource)};}return{url:'',type:''};}function getResourceContentLength(resource){if(isResponse(resource)){return resource.headers['content-length']||-1;}if(isBlob(resource)){return resource.size;}if(typeof resource==='string'){return resource.length;}if(resource instanceof ArrayBuffer){return resource.byteLength;}if(ArrayBuffer.isView(resource)){return resource.byteLength;}return-1;}function stripQueryString(url){return url.replace(QUERY_STRING_PATTERN,'');}function makeResponse(_x20){return _makeResponse.apply(this,arguments);}function _makeResponse(){_makeResponse=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee12(resource){var headers,contentLength,_getResourceUrlAndTyp3,url,type,initialDataUrl,response;return _regeneratorRuntime().wrap(function _callee12$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:if(!isResponse(resource)){_context16.next=2;break;}return _context16.abrupt("return",resource);case 2:headers={};contentLength=getResourceContentLength(resource);if(contentLength>=0){headers['content-length']=String(contentLength);}_getResourceUrlAndTyp3=getResourceUrlAndType(resource),url=_getResourceUrlAndTyp3.url,type=_getResourceUrlAndTyp3.type;if(type){headers['content-type']=type;}_context16.next=9;return getInitialDataUrl(resource);case 9:initialDataUrl=_context16.sent;if(initialDataUrl){headers['x-first-bytes']=initialDataUrl;}if(typeof resource==='string'){resource=new TextEncoder().encode(resource);}response=new Response(resource,{headers:headers});Object.defineProperty(response,'url',{value:url});return _context16.abrupt("return",response);case 15:case"end":return _context16.stop();}}},_callee12);}));return _makeResponse.apply(this,arguments);}function checkResponse(_x21){return _checkResponse.apply(this,arguments);}function _checkResponse(){_checkResponse=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee13(response){var message;return _regeneratorRuntime().wrap(function _callee13$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:if(response.ok){_context17.next=5;break;}_context17.next=3;return getResponseError(response);case 3:message=_context17.sent;throw new Error(message);case 5:case"end":return _context17.stop();}}},_callee13);}));return _checkResponse.apply(this,arguments);}function getResponseError(_x22){return _getResponseError.apply(this,arguments);}function _getResponseError(){_getResponseError=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee14(response){var message,contentType,text;return _regeneratorRuntime().wrap(function _callee14$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:message="Failed to fetch resource ".concat(response.url," (").concat(response.status,"): ");_context18.prev=1;contentType=response.headers.get('Content-Type');text=response.statusText;if(!contentType.includes('application/json')){_context18.next=11;break;}_context18.t0=text;_context18.t1=" ";_context18.next=9;return response.text();case 9:_context18.t2=_context18.sent;text=_context18.t0+=_context18.t1.concat.call(_context18.t1,_context18.t2);case 11:message+=text;message=message.length>60?"".concat(message.slice(0,60),"..."):message;_context18.next=17;break;case 15:_context18.prev=15;_context18.t3=_context18["catch"](1);case 17:return _context18.abrupt("return",message);case 18:case"end":return _context18.stop();}}},_callee14,null,[[1,15]]);}));return _getResponseError.apply(this,arguments);}function getInitialDataUrl(_x23){return _getInitialDataUrl.apply(this,arguments);}function _getInitialDataUrl(){_getInitialDataUrl=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee15(resource){var INITIAL_DATA_LENGTH,blobSlice,slice,_base;return _regeneratorRuntime().wrap(function _callee15$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:INITIAL_DATA_LENGTH=5;if(!(typeof resource==='string')){_context19.next=3;break;}return _context19.abrupt("return","data:,".concat(resource.slice(0,INITIAL_DATA_LENGTH)));case 3:if(!(resource instanceof Blob)){_context19.next=8;break;}blobSlice=resource.slice(0,5);_context19.next=7;return new Promise(function(resolve){var reader=new FileReader();reader.onload=function(event){var _event$target;return resolve(event===null||event===void 0?void 0:(_event$target=event.target)===null||_event$target===void 0?void 0:_event$target.result);};reader.readAsDataURL(blobSlice);});case 7:return _context19.abrupt("return",_context19.sent);case 8:if(!(resource instanceof ArrayBuffer)){_context19.next=12;break;}slice=resource.slice(0,INITIAL_DATA_LENGTH);_base=arrayBufferToBase64(slice);return _context19.abrupt("return","data:base64,".concat(_base));case 12:return _context19.abrupt("return",null);case 13:case"end":return _context19.stop();}}},_callee15);}));return _getInitialDataUrl.apply(this,arguments);}function arrayBufferToBase64(buffer){var binary='';var bytes=new Uint8Array(buffer);for(var _i498=0;_i498=0){return true;}return false;}function isBrowser$2(){var isNode=(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&String(process)==='[object process]'&&!process.browser;return!isNode||isElectron$1();}var globals$1={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&process};var window_$1=globals$1.window||globals$1.self||globals$1.global;var process_$1=globals$1.process||{};var VERSION$7=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';var isBrowser$1=isBrowser$2();function getStorage$1(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}var LocalStorage$1=/*#__PURE__*/function(){function LocalStorage$1(id,defaultSettings){var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_classCallCheck(this,LocalStorage$1);this.storage=getStorage$1(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}_createClass(LocalStorage$1,[{key:"getConfiguration",value:function getConfiguration(){return this.config;}},{key:"setConfiguration",value:function setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}},{key:"updateConfiguration",value:function updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}},{key:"_loadConfiguration",value:function _loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}]);return LocalStorage$1;}();function formatTime$1(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else{formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad$1(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return"".concat(' '.repeat(padLength)).concat(string);}function formatImage$1(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return["".concat(message," %c+"),style];}var COLOR$1={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function getColor$1(color){return typeof color==='string'?COLOR$1[color.toUpperCase()]||COLOR$1.WHITE:color;}function addColor$1(string,color,background){if(!isBrowser$1&&typeof string==='string'){if(color){color=getColor$1(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor$1(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind$1(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _iterator7=_createForOfIteratorHelper(propNames),_step7;try{var _loop4=function _loop4(){var key=_step7.value;if(typeof obj[key]==='function'){if(!predefined.find(function(name){return key===name;})){obj[key]=obj[key].bind(obj);}}};for(_iterator7.s();!(_step7=_iterator7.n()).done;){_loop4();}}catch(err){_iterator7.e(err);}finally{_iterator7.f();}}function assert$3(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp$1(){var timestamp;if(isBrowser$1&&window_$1.performance){timestamp=window_$1.performance.now();}else if(process_$1.hrtime){var timeParts=process_$1.hrtime();timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else{timestamp=Date.now();}return timestamp;}var originalConsole$1={debug:isBrowser$1?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS$1={enabled:true,level:0};function noop$1(){}var cache$1={};var ONCE$1={once:true};function getTableHeader$1(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return'empty';}var Log$1=/*#__PURE__*/function(){function Log$1(){var _ref16=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''},id=_ref16.id;_classCallCheck(this,Log$1);this.id=id;this.VERSION=VERSION$7;this._startTs=getHiResTimestamp$1();this._deltaTs=getHiResTimestamp$1();this.LOG_THROTTLE_TIMEOUT=0;this._storage=new LocalStorage$1("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS$1);this.userData={};this.timeStamp("".concat(this.id," started"));autobind$1(this);Object.seal(this);}_createClass(Log$1,[{key:"level",get:function get(){return this.getLevel();},set:function set(newLevel){this.setLevel(newLevel);}},{key:"isEnabled",value:function isEnabled(){return this._storage.config.enabled;}},{key:"getLevel",value:function getLevel(){return this._storage.config.level;}},{key:"getTotal",value:function getTotal(){return Number((getHiResTimestamp$1()-this._startTs).toPrecision(10));}},{key:"getDelta",value:function getDelta(){return Number((getHiResTimestamp$1()-this._deltaTs).toPrecision(10));}},{key:"priority",get:function get(){return this.level;},set:function set(newPriority){this.level=newPriority;}},{key:"getPriority",value:function getPriority(){return this.level;}},{key:"enable",value:function enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled:enabled});return this;}},{key:"setLevel",value:function setLevel(level){this._storage.updateConfiguration({level:level});return this;}},{key:"assert",value:function assert(condition,message){assert$3(condition,message);}},{key:"warn",value:function warn(message){return this._getLogFunction(0,message,originalConsole$1.warn,arguments,ONCE$1);}},{key:"error",value:function error(message){return this._getLogFunction(0,message,originalConsole$1.error,arguments);}},{key:"deprecated",value:function deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}},{key:"removed",value:function removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}},{key:"probe",value:function probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.log,arguments,{time:true,once:true});}},{key:"log",value:function log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.debug,arguments);}},{key:"info",value:function info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}},{key:"once",value:function once(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole$1.debug||originalConsole$1.info,arguments,ONCE$1);}},{key:"table",value:function table(logLevel,_table,columns){if(_table){return this._getLogFunction(logLevel,_table,console.table||noop$1,columns&&[columns],{tag:getTableHeader$1(_table)});}return noop$1;}},{key:"image",value:function(_image6){function image(_x26){return _image6.apply(this,arguments);}image.toString=function(){return _image6.toString();};return image;}(function(_ref17){var logLevel=_ref17.logLevel,priority=_ref17.priority,image=_ref17.image,_ref17$message=_ref17.message,message=_ref17$message===void 0?'':_ref17$message,_ref17$scale=_ref17.scale,scale=_ref17$scale===void 0?1:_ref17$scale;if(!this._shouldLog(logLevel||priority)){return noop$1;}return isBrowser$1?logImageInBrowser$1({image:image,message:message,scale:scale}):logImageInNode$1({image:image,message:message,scale:scale});})},{key:"settings",value:function settings(){if(console.table){console.table(this._storage.config);}else{console.log(this._storage.config);}}},{key:"get",value:function get(setting){return this._storage.config[setting];}},{key:"set",value:function set(setting,value){this._storage.updateConfiguration(_defineProperty2({},setting,value));}},{key:"time",value:function time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}},{key:"timeEnd",value:function timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}},{key:"timeStamp",value:function timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop$1);}},{key:"group",value:function group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};opts=normalizeArguments$1({logLevel:logLevel,message:message,opts:opts});var _opts=opts,collapsed=_opts.collapsed;opts.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(opts);}},{key:"groupCollapsed",value:function groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}},{key:"groupEnd",value:function groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop$1);}},{key:"withGroup",value:function withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}},{key:"trace",value:function trace(){if(console.trace){console.trace();}}},{key:"_shouldLog",value:function _shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel$1(logLevel);}},{key:"_getLogFunction",value:function _getLogFunction(logLevel,message,method){var args=arguments.length>3&&arguments[3]!==undefined?arguments[3]:[];var opts=arguments.length>4?arguments[4]:undefined;if(this._shouldLog(logLevel)){var _method;opts=normalizeArguments$1({logLevel:logLevel,message:message,args:args,opts:opts});method=method||opts.method;assert$3(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp$1();var tag=opts.tag||opts.message;if(opts.once){if(!cache$1[tag]){cache$1[tag]=getHiResTimestamp$1();}else{return noop$1;}}message=decorateMessage$1(this.id,opts.message,opts);return(_method=method).bind.apply(_method,[console,message].concat(_toConsumableArray(opts.args)));}return noop$1;}}]);return Log$1;}();Log$1.VERSION=VERSION$7;function normalizeLogLevel$1(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(_typeof(logLevel)){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$3(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments$1(opts){var logLevel=opts.logLevel,message=opts.message;opts.logLevel=normalizeLogLevel$1(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}opts.args=args;switch(_typeof(logLevel)){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=_typeof(opts.message);assert$3(messageType==='string'||messageType==='object');return Object.assign(opts,opts.opts);}function decorateMessage$1(id,message,opts){if(typeof message==='string'){var _time=opts.time?leftPad$1(formatTime$1(opts.total)):'';message=opts.time?"".concat(id,": ").concat(_time," ").concat(message):"".concat(id,": ").concat(message);message=addColor$1(message,opts.color,opts.background);}return message;}function logImageInNode$1(_ref18){var image=_ref18.image,_ref18$message=_ref18.message,message=_ref18$message===void 0?'':_ref18$message,_ref18$scale=_ref18.scale,scale=_ref18$scale===void 0?1:_ref18$scale;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return function(){return asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(function(data){return console.log(data);});};}return noop$1;}function logImageInBrowser$1(_ref19){var image=_ref19.image,_ref19$message=_ref19.message,message=_ref19$message===void 0?'':_ref19$message,_ref19$scale=_ref19.scale,scale=_ref19$scale===void 0?1:_ref19$scale;if(typeof image==='string'){var img=new Image();img.onload=function(){var _console;var args=formatImage$1(img,message,scale);(_console=console).log.apply(_console,_toConsumableArray(args));};img.src=image;return noop$1;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){var _console2;(_console2=console).log.apply(_console2,_toConsumableArray(formatImage$1(image,message,scale)));return noop$1;}if(element.toLowerCase()==='canvas'){var _img=new Image();_img.onload=function(){var _console3;return(_console3=console).log.apply(_console3,_toConsumableArray(formatImage$1(_img,message,scale)));};_img.src=image.toDataURL();return noop$1;}return noop$1;}var probeLog=new Log$1({id:'loaders.gl'});var NullLog=/*#__PURE__*/function(){function NullLog(){_classCallCheck(this,NullLog);}_createClass(NullLog,[{key:"log",value:function log(){return function(){};}},{key:"info",value:function info(){return function(){};}},{key:"warn",value:function warn(){return function(){};}},{key:"error",value:function error(){return function(){};}}]);return NullLog;}();var ConsoleLog=/*#__PURE__*/function(){function ConsoleLog(){_classCallCheck(this,ConsoleLog);_defineProperty(this,"console",void 0);this.console=console;}_createClass(ConsoleLog,[{key:"log",value:function log(){var _this$console$log;for(var _len103=arguments.length,args=new Array(_len103),_key7=0;_key7<_len103;_key7++){args[_key7]=arguments[_key7];}return(_this$console$log=this.console.log).bind.apply(_this$console$log,[this.console].concat(args));}},{key:"info",value:function info(){var _this$console$info;for(var _len104=arguments.length,args=new Array(_len104),_key8=0;_key8<_len104;_key8++){args[_key8]=arguments[_key8];}return(_this$console$info=this.console.info).bind.apply(_this$console$info,[this.console].concat(args));}},{key:"warn",value:function warn(){var _this$console$warn;for(var _len105=arguments.length,args=new Array(_len105),_key9=0;_key9<_len105;_key9++){args[_key9]=arguments[_key9];}return(_this$console$warn=this.console.warn).bind.apply(_this$console$warn,[this.console].concat(args));}},{key:"error",value:function error(){var _this$console$error;for(var _len106=arguments.length,args=new Array(_len106),_key10=0;_key10<_len106;_key10++){args[_key10]=arguments[_key10];}return(_this$console$error=this.console.error).bind.apply(_this$console$error,[this.console].concat(args));}}]);return ConsoleLog;}();var DEFAULT_LOADER_OPTIONS={fetch:null,mimeType:undefined,nothrow:false,log:new ConsoleLog(),CDN:'https://unpkg.com/@loaders.gl',worker:true,maxConcurrency:3,maxMobileConcurrency:1,reuseWorkers:isBrowser$4,_nodeWorkers:false,_workerType:'',limit:0,_limitMB:0,batchSize:'auto',batchDebounceMs:0,metadata:false,transforms:[]};var REMOVED_LOADER_OPTIONS={"throws":'nothrow',dataType:'(no longer used)',uri:'baseUri',method:'fetch.method',headers:'fetch.headers',body:'fetch.body',mode:'fetch.mode',credentials:'fetch.credentials',cache:'fetch.cache',redirect:'fetch.redirect',referrer:'fetch.referrer',referrerPolicy:'fetch.referrerPolicy',integrity:'fetch.integrity',keepalive:'fetch.keepalive',signal:'fetch.signal'};function getGlobalLoaderState(){globalThis.loaders=globalThis.loaders||{};var loaders=globalThis.loaders;loaders._state=loaders._state||{};return loaders._state;}var getGlobalLoaderOptions=function getGlobalLoaderOptions(){var state=getGlobalLoaderState();state.globalOptions=state.globalOptions||_objectSpread({},DEFAULT_LOADER_OPTIONS);return state.globalOptions;};function normalizeOptions(options,loader,loaders,url){loaders=loaders||[];loaders=Array.isArray(loaders)?loaders:[loaders];validateOptions(options,loaders);return normalizeOptionsInternal(loader,options,url);}function getFetchFunction(options,context){var globalOptions=getGlobalLoaderOptions();var fetchOptions=options||globalOptions;if(typeof fetchOptions.fetch==='function'){return fetchOptions.fetch;}if(isObject(fetchOptions.fetch)){return function(url){return fetchFile(url,fetchOptions);};}if(context!==null&&context!==void 0&&context.fetch){return context===null||context===void 0?void 0:context.fetch;}return fetchFile;}function validateOptions(options,loaders){validateOptionsObject(options,null,DEFAULT_LOADER_OPTIONS,REMOVED_LOADER_OPTIONS,loaders);var _iterator8=_createForOfIteratorHelper(loaders),_step8;try{for(_iterator8.s();!(_step8=_iterator8.n()).done;){var loader=_step8.value;var idOptions=options&&options[loader.id]||{};var loaderOptions=loader.options&&loader.options[loader.id]||{};var deprecatedOptions=loader.deprecatedOptions&&loader.deprecatedOptions[loader.id]||{};validateOptionsObject(idOptions,loader.id,loaderOptions,deprecatedOptions,loaders);}}catch(err){_iterator8.e(err);}finally{_iterator8.f();}}function validateOptionsObject(options,id,defaultOptions,deprecatedOptions,loaders){var loaderName=id||'Top level';var prefix=id?"".concat(id,"."):'';for(var key in options){var isSubOptions=!id&&isObject(options[key]);var isBaseUriOption=key==='baseUri'&&!id;var isWorkerUrlOption=key==='workerUrl'&&id;if(!(key in defaultOptions)&&!isBaseUriOption&&!isWorkerUrlOption){if(key in deprecatedOptions){probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' no longer supported, use '").concat(deprecatedOptions[key],"'"))();}else if(!isSubOptions){var suggestion=findSimilarOption(key,loaders);probeLog.warn("".concat(loaderName," loader option '").concat(prefix).concat(key,"' not recognized. ").concat(suggestion))();}}}}function findSimilarOption(optionKey,loaders){var lowerCaseOptionKey=optionKey.toLowerCase();var bestSuggestion='';var _iterator9=_createForOfIteratorHelper(loaders),_step9;try{for(_iterator9.s();!(_step9=_iterator9.n()).done;){var loader=_step9.value;for(var key in loader.options){if(optionKey===key){return"Did you mean '".concat(loader.id,".").concat(key,"'?");}var lowerCaseKey=key.toLowerCase();var isPartialMatch=lowerCaseOptionKey.startsWith(lowerCaseKey)||lowerCaseKey.startsWith(lowerCaseOptionKey);if(isPartialMatch){bestSuggestion=bestSuggestion||"Did you mean '".concat(loader.id,".").concat(key,"'?");}}}}catch(err){_iterator9.e(err);}finally{_iterator9.f();}return bestSuggestion;}function normalizeOptionsInternal(loader,options,url){var loaderDefaultOptions=loader.options||{};var mergedOptions=_objectSpread({},loaderDefaultOptions);addUrlOptions(mergedOptions,url);if(mergedOptions.log===null){mergedOptions.log=new NullLog();}mergeNestedFields(mergedOptions,getGlobalLoaderOptions());mergeNestedFields(mergedOptions,options);return mergedOptions;}function mergeNestedFields(mergedOptions,options){for(var key in options){if(key in options){var value=options[key];if(isPureObject(value)&&isPureObject(mergedOptions[key])){mergedOptions[key]=_objectSpread(_objectSpread({},mergedOptions[key]),options[key]);}else{mergedOptions[key]=options[key];}}}}function addUrlOptions(options,url){if(url&&!('baseUri'in options)){options.baseUri=url;}}function isLoaderObject(loader){var _loader;if(!loader){return false;}if(Array.isArray(loader)){loader=loader[0];}var hasExtensions=Array.isArray((_loader=loader)===null||_loader===void 0?void 0:_loader.extensions);return hasExtensions;}function normalizeLoader(loader){var _loader2,_loader3;assert$5(loader,'null loader');assert$5(isLoaderObject(loader),'invalid loader');var options;if(Array.isArray(loader)){options=loader[1];loader=loader[0];loader=_objectSpread(_objectSpread({},loader),{},{options:_objectSpread(_objectSpread({},loader.options),options)});}if((_loader2=loader)!==null&&_loader2!==void 0&&_loader2.parseTextSync||(_loader3=loader)!==null&&_loader3!==void 0&&_loader3.parseText){loader.text=true;}if(!loader.text){loader.binary=true;}return loader;}var getGlobalLoaderRegistry=function getGlobalLoaderRegistry(){var state=getGlobalLoaderState();state.loaderRegistry=state.loaderRegistry||[];return state.loaderRegistry;};function getRegisteredLoaders(){return getGlobalLoaderRegistry();}function isElectron(mockUserAgent){if(typeof window!=='undefined'&&_typeof(window.process)==='object'&&window.process.type==='renderer'){return true;}if(typeof process!=='undefined'&&_typeof(process.versions)==='object'&&Boolean(process.versions.electron)){return true;}var realUserAgent=(typeof navigator==="undefined"?"undefined":_typeof(navigator))==='object'&&typeof navigator.userAgent==='string'&&navigator.userAgent;var userAgent=mockUserAgent||realUserAgent;if(userAgent&&userAgent.indexOf('Electron')>=0){return true;}return false;}function isBrowser(){var isNode=(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&String(process)==='[object process]'&&!process.browser;return!isNode||isElectron();}var globals={self:typeof self!=='undefined'&&self,window:typeof window!=='undefined'&&window,global:typeof global!=='undefined'&&global,document:typeof document!=='undefined'&&document,process:(typeof process==="undefined"?"undefined":_typeof(process))==='object'&&process};var window_=globals.window||globals.self||globals.global;var process_=globals.process||{};var VERSION$6=typeof __VERSION__!=='undefined'?__VERSION__:'untranspiled source';isBrowser();function getStorage(type){try{var storage=window[type];var x='__storage_test__';storage.setItem(x,x);storage.removeItem(x);return storage;}catch(e){return null;}}var LocalStorage=/*#__PURE__*/function(){function LocalStorage(id){_classCallCheck(this,LocalStorage);var defaultSettings=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var type=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'sessionStorage';_defineProperty(this,"storage",void 0);_defineProperty(this,"id",void 0);_defineProperty(this,"config",{});this.storage=getStorage(type);this.id=id;this.config={};Object.assign(this.config,defaultSettings);this._loadConfiguration();}_createClass(LocalStorage,[{key:"getConfiguration",value:function getConfiguration(){return this.config;}},{key:"setConfiguration",value:function setConfiguration(configuration){this.config={};return this.updateConfiguration(configuration);}},{key:"updateConfiguration",value:function updateConfiguration(configuration){Object.assign(this.config,configuration);if(this.storage){var serialized=JSON.stringify(this.config);this.storage.setItem(this.id,serialized);}return this;}},{key:"_loadConfiguration",value:function _loadConfiguration(){var configuration={};if(this.storage){var serializedConfiguration=this.storage.getItem(this.id);configuration=serializedConfiguration?JSON.parse(serializedConfiguration):{};}Object.assign(this.config,configuration);return this;}}]);return LocalStorage;}();function formatTime(ms){var formatted;if(ms<10){formatted="".concat(ms.toFixed(2),"ms");}else if(ms<100){formatted="".concat(ms.toFixed(1),"ms");}else if(ms<1000){formatted="".concat(ms.toFixed(0),"ms");}else{formatted="".concat((ms/1000).toFixed(2),"s");}return formatted;}function leftPad(string){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:8;var padLength=Math.max(length-string.length,0);return"".concat(' '.repeat(padLength)).concat(string);}function formatImage(image,message,scale){var maxWidth=arguments.length>3&&arguments[3]!==undefined?arguments[3]:600;var imageUrl=image.src.replace(/\(/g,'%28').replace(/\)/g,'%29');if(image.width>maxWidth){scale=Math.min(scale,maxWidth/image.width);}var width=image.width*scale;var height=image.height*scale;var style=['font-size:1px;',"padding:".concat(Math.floor(height/2),"px ").concat(Math.floor(width/2),"px;"),"line-height:".concat(height,"px;"),"background:url(".concat(imageUrl,");"),"background-size:".concat(width,"px ").concat(height,"px;"),'color:transparent;'].join('');return["".concat(message," %c+"),style];}var COLOR;(function(COLOR){COLOR[COLOR["BLACK"]=30]="BLACK";COLOR[COLOR["RED"]=31]="RED";COLOR[COLOR["GREEN"]=32]="GREEN";COLOR[COLOR["YELLOW"]=33]="YELLOW";COLOR[COLOR["BLUE"]=34]="BLUE";COLOR[COLOR["MAGENTA"]=35]="MAGENTA";COLOR[COLOR["CYAN"]=36]="CYAN";COLOR[COLOR["WHITE"]=37]="WHITE";COLOR[COLOR["BRIGHT_BLACK"]=90]="BRIGHT_BLACK";COLOR[COLOR["BRIGHT_RED"]=91]="BRIGHT_RED";COLOR[COLOR["BRIGHT_GREEN"]=92]="BRIGHT_GREEN";COLOR[COLOR["BRIGHT_YELLOW"]=93]="BRIGHT_YELLOW";COLOR[COLOR["BRIGHT_BLUE"]=94]="BRIGHT_BLUE";COLOR[COLOR["BRIGHT_MAGENTA"]=95]="BRIGHT_MAGENTA";COLOR[COLOR["BRIGHT_CYAN"]=96]="BRIGHT_CYAN";COLOR[COLOR["BRIGHT_WHITE"]=97]="BRIGHT_WHITE";})(COLOR||(COLOR={}));function getColor(color){return typeof color==='string'?COLOR[color.toUpperCase()]||COLOR.WHITE:color;}function addColor(string,color,background){if(!isBrowser&&typeof string==='string'){if(color){color=getColor(color);string="\x1B[".concat(color,"m").concat(string,"\x1B[39m");}if(background){color=getColor(background);string="\x1B[".concat(background+10,"m").concat(string,"\x1B[49m");}}return string;}function autobind(obj){var predefined=arguments.length>1&&arguments[1]!==undefined?arguments[1]:['constructor'];var proto=Object.getPrototypeOf(obj);var propNames=Object.getOwnPropertyNames(proto);var _iterator10=_createForOfIteratorHelper(propNames),_step10;try{var _loop5=function _loop5(){var key=_step10.value;if(typeof obj[key]==='function'){if(!predefined.find(function(name){return key===name;})){obj[key]=obj[key].bind(obj);}}};for(_iterator10.s();!(_step10=_iterator10.n()).done;){_loop5();}}catch(err){_iterator10.e(err);}finally{_iterator10.f();}}function assert$2(condition,message){if(!condition){throw new Error(message||'Assertion failed');}}function getHiResTimestamp(){var timestamp;if(isBrowser&&'performance'in window_){var _window$performance,_window$performance$n;timestamp=window_===null||window_===void 0?void 0:(_window$performance=window_.performance)===null||_window$performance===void 0?void 0:(_window$performance$n=_window$performance.now)===null||_window$performance$n===void 0?void 0:_window$performance$n.call(_window$performance);}else if('hrtime'in process_){var _process$hrtime;var timeParts=process_===null||process_===void 0?void 0:(_process$hrtime=process_.hrtime)===null||_process$hrtime===void 0?void 0:_process$hrtime.call(process_);timestamp=timeParts[0]*1000+timeParts[1]/1e6;}else{timestamp=Date.now();}return timestamp;}var originalConsole={debug:isBrowser?console.debug||console.log:console.log,log:console.log,info:console.info,warn:console.warn,error:console.error};var DEFAULT_SETTINGS={enabled:true,level:0};function noop(){}var cache={};var ONCE={once:true};var Log=/*#__PURE__*/function(){function Log(){_classCallCheck(this,Log);var _ref20=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{id:''},id=_ref20.id;_defineProperty(this,"id",void 0);_defineProperty(this,"VERSION",VERSION$6);_defineProperty(this,"_startTs",getHiResTimestamp());_defineProperty(this,"_deltaTs",getHiResTimestamp());_defineProperty(this,"_storage",void 0);_defineProperty(this,"userData",{});_defineProperty(this,"LOG_THROTTLE_TIMEOUT",0);this.id=id;this._storage=new LocalStorage("__probe-".concat(this.id,"__"),DEFAULT_SETTINGS);this.userData={};this.timeStamp("".concat(this.id," started"));autobind(this);Object.seal(this);}_createClass(Log,[{key:"level",get:function get(){return this.getLevel();},set:function set(newLevel){this.setLevel(newLevel);}},{key:"isEnabled",value:function isEnabled(){return this._storage.config.enabled;}},{key:"getLevel",value:function getLevel(){return this._storage.config.level;}},{key:"getTotal",value:function getTotal(){return Number((getHiResTimestamp()-this._startTs).toPrecision(10));}},{key:"getDelta",value:function getDelta(){return Number((getHiResTimestamp()-this._deltaTs).toPrecision(10));}},{key:"priority",get:function get(){return this.level;},set:function set(newPriority){this.level=newPriority;}},{key:"getPriority",value:function getPriority(){return this.level;}},{key:"enable",value:function enable(){var enabled=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;this._storage.updateConfiguration({enabled:enabled});return this;}},{key:"setLevel",value:function setLevel(level){this._storage.updateConfiguration({level:level});return this;}},{key:"get",value:function get(setting){return this._storage.config[setting];}},{key:"set",value:function set(setting,value){this._storage.updateConfiguration(_defineProperty2({},setting,value));}},{key:"settings",value:function settings(){if(console.table){console.table(this._storage.config);}else{console.log(this._storage.config);}}},{key:"assert",value:function assert(condition,message){assert$2(condition,message);}},{key:"warn",value:function warn(message){return this._getLogFunction(0,message,originalConsole.warn,arguments,ONCE);}},{key:"error",value:function error(message){return this._getLogFunction(0,message,originalConsole.error,arguments);}},{key:"deprecated",value:function deprecated(oldUsage,newUsage){return this.warn("`".concat(oldUsage,"` is deprecated and will be removed in a later version. Use `").concat(newUsage,"` instead"));}},{key:"removed",value:function removed(oldUsage,newUsage){return this.error("`".concat(oldUsage,"` has been removed. Use `").concat(newUsage,"` instead"));}},{key:"probe",value:function probe(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.log,arguments,{time:true,once:true});}},{key:"log",value:function log(logLevel,message){return this._getLogFunction(logLevel,message,originalConsole.debug,arguments);}},{key:"info",value:function info(logLevel,message){return this._getLogFunction(logLevel,message,console.info,arguments);}},{key:"once",value:function once(logLevel,message){for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}return this._getLogFunction(logLevel,message,originalConsole.debug||originalConsole.info,arguments,ONCE);}},{key:"table",value:function table(logLevel,_table2,columns){if(_table2){return this._getLogFunction(logLevel,_table2,console.table||noop,columns&&[columns],{tag:getTableHeader(_table2)});}return noop;}},{key:"image",value:function image(_ref){var logLevel=_ref.logLevel,priority=_ref.priority,image=_ref.image,_ref$message=_ref.message,message=_ref$message===void 0?'':_ref$message,_ref$scale=_ref.scale,scale=_ref$scale===void 0?1:_ref$scale;if(!this._shouldLog(logLevel||priority)){return noop;}return isBrowser?logImageInBrowser({image:image,message:message,scale:scale}):logImageInNode({image:image,message:message,scale:scale});}},{key:"time",value:function time(logLevel,message){return this._getLogFunction(logLevel,message,console.time?console.time:console.info);}},{key:"timeEnd",value:function timeEnd(logLevel,message){return this._getLogFunction(logLevel,message,console.timeEnd?console.timeEnd:console.info);}},{key:"timeStamp",value:function timeStamp(logLevel,message){return this._getLogFunction(logLevel,message,console.timeStamp||noop);}},{key:"group",value:function group(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{collapsed:false};var options=normalizeArguments({logLevel:logLevel,message:message,opts:opts});var collapsed=opts.collapsed;options.method=(collapsed?console.groupCollapsed:console.group)||console.info;return this._getLogFunction(options);}},{key:"groupCollapsed",value:function groupCollapsed(logLevel,message){var opts=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.group(logLevel,message,Object.assign({},opts,{collapsed:true}));}},{key:"groupEnd",value:function groupEnd(logLevel){return this._getLogFunction(logLevel,'',console.groupEnd||noop);}},{key:"withGroup",value:function withGroup(logLevel,message,func){this.group(logLevel,message)();try{func();}finally{this.groupEnd(logLevel)();}}},{key:"trace",value:function trace(){if(console.trace){console.trace();}}},{key:"_shouldLog",value:function _shouldLog(logLevel){return this.isEnabled()&&this.getLevel()>=normalizeLogLevel(logLevel);}},{key:"_getLogFunction",value:function _getLogFunction(logLevel,message,method,args,opts){if(this._shouldLog(logLevel)){var _method2;opts=normalizeArguments({logLevel:logLevel,message:message,args:args,opts:opts});method=method||opts.method;assert$2(method);opts.total=this.getTotal();opts.delta=this.getDelta();this._deltaTs=getHiResTimestamp();var tag=opts.tag||opts.message;if(opts.once){if(!cache[tag]){cache[tag]=getHiResTimestamp();}else{return noop;}}message=decorateMessage(this.id,opts.message,opts);return(_method2=method).bind.apply(_method2,[console,message].concat(_toConsumableArray(opts.args)));}return noop;}}]);return Log;}();_defineProperty(Log,"VERSION",VERSION$6);function normalizeLogLevel(logLevel){if(!logLevel){return 0;}var resolvedLevel;switch(_typeof(logLevel)){case'number':resolvedLevel=logLevel;break;case'object':resolvedLevel=logLevel.logLevel||logLevel.priority||0;break;default:return 0;}assert$2(Number.isFinite(resolvedLevel)&&resolvedLevel>=0);return resolvedLevel;}function normalizeArguments(opts){var logLevel=opts.logLevel,message=opts.message;opts.logLevel=normalizeLogLevel(logLevel);var args=opts.args?Array.from(opts.args):[];while(args.length&&args.shift()!==message){}switch(_typeof(logLevel)){case'string':case'function':if(message!==undefined){args.unshift(message);}opts.message=logLevel;break;case'object':Object.assign(opts,logLevel);break;}if(typeof opts.message==='function'){opts.message=opts.message();}var messageType=_typeof(opts.message);assert$2(messageType==='string'||messageType==='object');return Object.assign(opts,{args:args},opts.opts);}function decorateMessage(id,message,opts){if(typeof message==='string'){var _time2=opts.time?leftPad(formatTime(opts.total)):'';message=opts.time?"".concat(id,": ").concat(_time2," ").concat(message):"".concat(id,": ").concat(message);message=addColor(message,opts.color,opts.background);}return message;}function logImageInNode(_ref2){var image=_ref2.image,_ref2$message=_ref2.message,message=_ref2$message===void 0?'':_ref2$message,_ref2$scale=_ref2.scale,scale=_ref2$scale===void 0?1:_ref2$scale;var asciify=null;try{asciify=module.require('asciify-image');}catch(error){}if(asciify){return function(){return asciify(image,{fit:'box',width:"".concat(Math.round(80*scale),"%")}).then(function(data){return console.log(data);});};}return noop;}function logImageInBrowser(_ref3){var image=_ref3.image,_ref3$message=_ref3.message,message=_ref3$message===void 0?'':_ref3$message,_ref3$scale=_ref3.scale,scale=_ref3$scale===void 0?1:_ref3$scale;if(typeof image==='string'){var img=new Image();img.onload=function(){var _console4;var args=formatImage(img,message,scale);(_console4=console).log.apply(_console4,_toConsumableArray(args));};img.src=image;return noop;}var element=image.nodeName||'';if(element.toLowerCase()==='img'){var _console5;(_console5=console).log.apply(_console5,_toConsumableArray(formatImage(image,message,scale)));return noop;}if(element.toLowerCase()==='canvas'){var _img2=new Image();_img2.onload=function(){var _console6;return(_console6=console).log.apply(_console6,_toConsumableArray(formatImage(_img2,message,scale)));};_img2.src=image.toDataURL();return noop;}return noop;}function getTableHeader(table){for(var key in table){for(var title in table[key]){return title||'untitled';}}return'empty';}var log=new Log({id:'loaders.gl'});var EXT_PATTERN=/\.([^.]+)$/;function selectLoader(_x27){return _selectLoader.apply(this,arguments);}function _selectLoader(){_selectLoader=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee17(data){var loaders,options,context,loader,_args15=arguments;return _regeneratorRuntime().wrap(function _callee17$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:loaders=_args15.length>1&&_args15[1]!==undefined?_args15[1]:[];options=_args15.length>2?_args15[2]:undefined;context=_args15.length>3?_args15[3]:undefined;if(validHTTPResponse(data)){_context21.next=5;break;}return _context21.abrupt("return",null);case 5:loader=selectLoaderSync(data,loaders,_objectSpread(_objectSpread({},options),{},{nothrow:true}),context);if(!loader){_context21.next=8;break;}return _context21.abrupt("return",loader);case 8:if(!isBlob(data)){_context21.next=13;break;}_context21.next=11;return data.slice(0,10).arrayBuffer();case 11:data=_context21.sent;loader=selectLoaderSync(data,loaders,options,context);case 13:if(!(!loader&&!(options!==null&&options!==void 0&&options.nothrow))){_context21.next=15;break;}throw new Error(getNoValidLoaderMessage(data));case 15:return _context21.abrupt("return",loader);case 16:case"end":return _context21.stop();}}},_callee17);}));return _selectLoader.apply(this,arguments);}function selectLoaderSync(data){var loaders=arguments.length>1&&arguments[1]!==undefined?arguments[1]:[];var options=arguments.length>2?arguments[2]:undefined;var context=arguments.length>3?arguments[3]:undefined;if(!validHTTPResponse(data)){return null;}if(loaders&&!Array.isArray(loaders)){return normalizeLoader(loaders);}var candidateLoaders=[];if(loaders){candidateLoaders=candidateLoaders.concat(loaders);}if(!(options!==null&&options!==void 0&&options.ignoreRegisteredLoaders)){var _candidateLoaders;(_candidateLoaders=candidateLoaders).push.apply(_candidateLoaders,_toConsumableArray(getRegisteredLoaders()));}normalizeLoaders(candidateLoaders);var loader=selectLoaderInternal(data,candidateLoaders,options,context);if(!loader&&!(options!==null&&options!==void 0&&options.nothrow)){throw new Error(getNoValidLoaderMessage(data));}return loader;}function selectLoaderInternal(data,loaders,options,context){var _getResourceUrlAndTyp=getResourceUrlAndType(data),url=_getResourceUrlAndTyp.url,type=_getResourceUrlAndTyp.type;var testUrl=url||(context===null||context===void 0?void 0:context.url);var loader=null;var reason='';if(options!==null&&options!==void 0&&options.mimeType){loader=findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.mimeType);reason="match forced by supplied MIME type ".concat(options===null||options===void 0?void 0:options.mimeType);}loader=loader||findLoaderByUrl(loaders,testUrl);reason=reason||(loader?"matched url ".concat(testUrl):'');loader=loader||findLoaderByMIMEType(loaders,type);reason=reason||(loader?"matched MIME type ".concat(type):'');loader=loader||findLoaderByInitialBytes(loaders,data);reason=reason||(loader?"matched initial data ".concat(getFirstCharacters(data)):'');loader=loader||findLoaderByMIMEType(loaders,options===null||options===void 0?void 0:options.fallbackMimeType);reason=reason||(loader?"matched fallback MIME type ".concat(type):'');if(reason){var _loader;log.log(1,"selectLoader selected ".concat((_loader=loader)===null||_loader===void 0?void 0:_loader.name,": ").concat(reason,"."));}return loader;}function validHTTPResponse(data){if(data instanceof Response){if(data.status===204){return false;}}return true;}function getNoValidLoaderMessage(data){var _getResourceUrlAndTyp2=getResourceUrlAndType(data),url=_getResourceUrlAndTyp2.url,type=_getResourceUrlAndTyp2.type;var message='No valid loader found (';message+=url?"".concat(filename(url),", "):'no url provided, ';message+="MIME type: ".concat(type?"\"".concat(type,"\""):'not provided',", ");var firstCharacters=data?getFirstCharacters(data):'';message+=firstCharacters?" first bytes: \"".concat(firstCharacters,"\""):'first bytes: not available';message+=')';return message;}function normalizeLoaders(loaders){var _iterator11=_createForOfIteratorHelper(loaders),_step11;try{for(_iterator11.s();!(_step11=_iterator11.n()).done;){var loader=_step11.value;normalizeLoader(loader);}}catch(err){_iterator11.e(err);}finally{_iterator11.f();}}function findLoaderByUrl(loaders,url){var match=url&&EXT_PATTERN.exec(url);var extension=match&&match[1];return extension?findLoaderByExtension(loaders,extension):null;}function findLoaderByExtension(loaders,extension){extension=extension.toLowerCase();var _iterator12=_createForOfIteratorHelper(loaders),_step12;try{for(_iterator12.s();!(_step12=_iterator12.n()).done;){var loader=_step12.value;var _iterator13=_createForOfIteratorHelper(loader.extensions),_step13;try{for(_iterator13.s();!(_step13=_iterator13.n()).done;){var loaderExtension=_step13.value;if(loaderExtension.toLowerCase()===extension){return loader;}}}catch(err){_iterator13.e(err);}finally{_iterator13.f();}}}catch(err){_iterator12.e(err);}finally{_iterator12.f();}return null;}function findLoaderByMIMEType(loaders,mimeType){var _iterator14=_createForOfIteratorHelper(loaders),_step14;try{for(_iterator14.s();!(_step14=_iterator14.n()).done;){var loader=_step14.value;if(loader.mimeTypes&&loader.mimeTypes.includes(mimeType)){return loader;}if(mimeType==="application/x.".concat(loader.id)){return loader;}}}catch(err){_iterator14.e(err);}finally{_iterator14.f();}return null;}function findLoaderByInitialBytes(loaders,data){if(!data){return null;}var _iterator15=_createForOfIteratorHelper(loaders),_step15;try{for(_iterator15.s();!(_step15=_iterator15.n()).done;){var loader=_step15.value;if(typeof data==='string'){if(testDataAgainstText(data,loader)){return loader;}}else if(ArrayBuffer.isView(data)){if(testDataAgainstBinary(data.buffer,data.byteOffset,loader)){return loader;}}else if(data instanceof ArrayBuffer){var byteOffset=0;if(testDataAgainstBinary(data,byteOffset,loader)){return loader;}}}}catch(err){_iterator15.e(err);}finally{_iterator15.f();}return null;}function testDataAgainstText(data,loader){if(loader.testText){return loader.testText(data);}var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(function(test){return data.startsWith(test);});}function testDataAgainstBinary(data,byteOffset,loader){var tests=Array.isArray(loader.tests)?loader.tests:[loader.tests];return tests.some(function(test){return testBinary(data,byteOffset,loader,test);});}function testBinary(data,byteOffset,loader,test){if(test instanceof ArrayBuffer){return compareArrayBuffers(test,data,test.byteLength);}switch(_typeof(test)){case'function':return test(data,loader);case'string':var magic=getMagicString$1(data,byteOffset,test.length);return test===magic;default:return false;}}function getFirstCharacters(data){var length=arguments.length>1&&arguments[1]!==undefined?arguments[1]:5;if(typeof data==='string'){return data.slice(0,length);}else if(ArrayBuffer.isView(data)){return getMagicString$1(data.buffer,data.byteOffset,length);}else if(data instanceof ArrayBuffer){var byteOffset=0;return getMagicString$1(data,byteOffset,length);}return'';}function getMagicString$1(arrayBuffer,byteOffset,length){if(arrayBuffer.byteLength1&&_args5[1]!==undefined?_args5[1]:{};_options$chunkSize=options.chunkSize,chunkSize=_options$chunkSize===void 0?DEFAULT_CHUNK_SIZE$1:_options$chunkSize;byteOffset=0;case 3:if(!(byteOffset2&&arguments[2]!==undefined?arguments[2]:null;if(previousContext){return previousContext;}var resolvedContext=_objectSpread({fetch:getFetchFunction(options,context)},context);if(!Array.isArray(resolvedContext.loaders)){resolvedContext.loaders=null;}return resolvedContext;}function getLoadersFromContext(loaders,context){if(!context&&loaders&&!Array.isArray(loaders)){return loaders;}var candidateLoaders;if(loaders){candidateLoaders=Array.isArray(loaders)?loaders:[loaders];}if(context&&context.loaders){var contextLoaders=Array.isArray(context.loaders)?context.loaders:[context.loaders];candidateLoaders=candidateLoaders?[].concat(_toConsumableArray(candidateLoaders),_toConsumableArray(contextLoaders)):contextLoaders;}return candidateLoaders&&candidateLoaders.length?candidateLoaders:null;}function parse$3(_x31,_x32,_x33,_x34){return _parse$.apply(this,arguments);}function _parse$(){_parse$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee19(data,loaders,options,context){var _getResourceUrlAndTyp4,url,typedLoaders,candidateLoaders,loader;return _regeneratorRuntime().wrap(function _callee19$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:assert$4(!context||_typeof(context)==='object');if(loaders&&!Array.isArray(loaders)&&!isLoaderObject(loaders)){context=undefined;options=loaders;loaders=undefined;}_context23.next=4;return data;case 4:data=_context23.sent;options=options||{};_getResourceUrlAndTyp4=getResourceUrlAndType(data),url=_getResourceUrlAndTyp4.url;typedLoaders=loaders;candidateLoaders=getLoadersFromContext(typedLoaders,context);_context23.next=11;return selectLoader(data,candidateLoaders,options);case 11:loader=_context23.sent;if(loader){_context23.next=14;break;}return _context23.abrupt("return",null);case 14:options=normalizeOptions(options,loader,candidateLoaders,url);context=getLoaderContext({url:url,parse:parse$3,loaders:candidateLoaders},options,context);_context23.next=18;return parseWithLoader(loader,data,options,context);case 18:return _context23.abrupt("return",_context23.sent);case 19:case"end":return _context23.stop();}}},_callee19);}));return _parse$.apply(this,arguments);}function parseWithLoader(_x35,_x36,_x37,_x38){return _parseWithLoader.apply(this,arguments);}function _parseWithLoader(){_parseWithLoader=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee20(loader,data,options,context){var response,ok,redirected,status,statusText,type,url,headers;return _regeneratorRuntime().wrap(function _callee20$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:validateWorkerVersion(loader);if(isResponse(data)){response=data;ok=response.ok,redirected=response.redirected,status=response.status,statusText=response.statusText,type=response.type,url=response.url;headers=Object.fromEntries(response.headers.entries());context.response={headers:headers,ok:ok,redirected:redirected,status:status,statusText:statusText,type:type,url:url};}_context24.next=4;return getArrayBufferOrStringFromData(data,loader,options);case 4:data=_context24.sent;if(!(loader.parseTextSync&&typeof data==='string')){_context24.next=8;break;}options.dataType='text';return _context24.abrupt("return",loader.parseTextSync(data,options,context,loader));case 8:if(!canParseWithWorker(loader,options)){_context24.next=12;break;}_context24.next=11;return parseWithWorker(loader,data,options,context,parse$3);case 11:return _context24.abrupt("return",_context24.sent);case 12:if(!(loader.parseText&&typeof data==='string')){_context24.next=16;break;}_context24.next=15;return loader.parseText(data,options,context,loader);case 15:return _context24.abrupt("return",_context24.sent);case 16:if(!loader.parse){_context24.next=20;break;}_context24.next=19;return loader.parse(data,options,context,loader);case 19:return _context24.abrupt("return",_context24.sent);case 20:assert$4(!loader.parseSync);throw new Error("".concat(loader.id," loader - no parser found and worker is disabled"));case 22:case"end":return _context24.stop();}}},_callee20);}));return _parseWithLoader.apply(this,arguments);}var VERSION$5="3.2.6";var VERSION$4="3.2.6";var VERSION$3="3.2.6";var BASIS_CDN_ENCODER_WASM="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$3,"/dist/libs/basis_encoder.wasm");var BASIS_CDN_ENCODER_JS="https://unpkg.com/@loaders.gl/textures@".concat(VERSION$3,"/dist/libs/basis_encoder.js");var loadBasisTranscoderPromise;function loadBasisTrascoderModule(_x39){return _loadBasisTrascoderModule.apply(this,arguments);}function _loadBasisTrascoderModule(){_loadBasisTrascoderModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee21(options){var modules;return _regeneratorRuntime().wrap(function _callee21$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:modules=options.modules||{};if(!modules.basis){_context25.next=3;break;}return _context25.abrupt("return",modules.basis);case 3:loadBasisTranscoderPromise=loadBasisTranscoderPromise||loadBasisTrascoder(options);_context25.next=6;return loadBasisTranscoderPromise;case 6:return _context25.abrupt("return",_context25.sent);case 7:case"end":return _context25.stop();}}},_callee21);}));return _loadBasisTrascoderModule.apply(this,arguments);}function loadBasisTrascoder(_x40){return _loadBasisTrascoder.apply(this,arguments);}function _loadBasisTrascoder(){_loadBasisTrascoder=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee22(options){var BASIS,wasmBinary,_yield$Promise$all,_yield$Promise$all2;return _regeneratorRuntime().wrap(function _callee22$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:BASIS=null;wasmBinary=null;_context26.t0=Promise;_context26.next=5;return loadLibrary('basis_transcoder.js','textures',options);case 5:_context26.t1=_context26.sent;_context26.next=8;return loadLibrary('basis_transcoder.wasm','textures',options);case 8:_context26.t2=_context26.sent;_context26.t3=[_context26.t1,_context26.t2];_context26.next=12;return _context26.t0.all.call(_context26.t0,_context26.t3);case 12:_yield$Promise$all=_context26.sent;_yield$Promise$all2=_slicedToArray(_yield$Promise$all,2);BASIS=_yield$Promise$all2[0];wasmBinary=_yield$Promise$all2[1];BASIS=BASIS||globalThis.BASIS;_context26.next=19;return initializeBasisTrascoderModule(BASIS,wasmBinary);case 19:return _context26.abrupt("return",_context26.sent);case 20:case"end":return _context26.stop();}}},_callee22);}));return _loadBasisTrascoder.apply(this,arguments);}function initializeBasisTrascoderModule(BasisModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(function(resolve){BasisModule(options).then(function(module){var BasisFile=module.BasisFile,initializeBasis=module.initializeBasis;initializeBasis();resolve({BasisFile:BasisFile});});});}var loadBasisEncoderPromise;function loadBasisEncoderModule(_x41){return _loadBasisEncoderModule.apply(this,arguments);}function _loadBasisEncoderModule(){_loadBasisEncoderModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee23(options){var modules;return _regeneratorRuntime().wrap(function _callee23$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:modules=options.modules||{};if(!modules.basisEncoder){_context27.next=3;break;}return _context27.abrupt("return",modules.basisEncoder);case 3:loadBasisEncoderPromise=loadBasisEncoderPromise||loadBasisEncoder(options);_context27.next=6;return loadBasisEncoderPromise;case 6:return _context27.abrupt("return",_context27.sent);case 7:case"end":return _context27.stop();}}},_callee23);}));return _loadBasisEncoderModule.apply(this,arguments);}function loadBasisEncoder(_x42){return _loadBasisEncoder.apply(this,arguments);}function _loadBasisEncoder(){_loadBasisEncoder=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee24(options){var BASIS_ENCODER,wasmBinary,_yield$Promise$all3,_yield$Promise$all4;return _regeneratorRuntime().wrap(function _callee24$(_context28){while(1){switch(_context28.prev=_context28.next){case 0:BASIS_ENCODER=null;wasmBinary=null;_context28.t0=Promise;_context28.next=5;return loadLibrary(BASIS_CDN_ENCODER_JS,'textures',options);case 5:_context28.t1=_context28.sent;_context28.next=8;return loadLibrary(BASIS_CDN_ENCODER_WASM,'textures',options);case 8:_context28.t2=_context28.sent;_context28.t3=[_context28.t1,_context28.t2];_context28.next=12;return _context28.t0.all.call(_context28.t0,_context28.t3);case 12:_yield$Promise$all3=_context28.sent;_yield$Promise$all4=_slicedToArray(_yield$Promise$all3,2);BASIS_ENCODER=_yield$Promise$all4[0];wasmBinary=_yield$Promise$all4[1];BASIS_ENCODER=BASIS_ENCODER||globalThis.BASIS;_context28.next=19;return initializeBasisEncoderModule(BASIS_ENCODER,wasmBinary);case 19:return _context28.abrupt("return",_context28.sent);case 20:case"end":return _context28.stop();}}},_callee24);}));return _loadBasisEncoder.apply(this,arguments);}function initializeBasisEncoderModule(BasisEncoderModule,wasmBinary){var options={};if(wasmBinary){options.wasmBinary=wasmBinary;}return new Promise(function(resolve){BasisEncoderModule(options).then(function(module){var BasisFile=module.BasisFile,KTX2File=module.KTX2File,initializeBasis=module.initializeBasis,BasisEncoder=module.BasisEncoder;initializeBasis();resolve({BasisFile:BasisFile,KTX2File:KTX2File,BasisEncoder:BasisEncoder});});});}var GL_EXTENSIONS_CONSTANTS={COMPRESSED_RGB_S3TC_DXT1_EXT:0x83f0,COMPRESSED_RGBA_S3TC_DXT1_EXT:0x83f1,COMPRESSED_RGBA_S3TC_DXT3_EXT:0x83f2,COMPRESSED_RGBA_S3TC_DXT5_EXT:0x83f3,COMPRESSED_R11_EAC:0x9270,COMPRESSED_SIGNED_R11_EAC:0x9271,COMPRESSED_RG11_EAC:0x9272,COMPRESSED_SIGNED_RG11_EAC:0x9273,COMPRESSED_RGB8_ETC2:0x9274,COMPRESSED_RGBA8_ETC2_EAC:0x9275,COMPRESSED_SRGB8_ETC2:0x9276,COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:0x9277,COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9278,COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:0x9279,COMPRESSED_RGB_PVRTC_4BPPV1_IMG:0x8c00,COMPRESSED_RGBA_PVRTC_4BPPV1_IMG:0x8c02,COMPRESSED_RGB_PVRTC_2BPPV1_IMG:0x8c01,COMPRESSED_RGBA_PVRTC_2BPPV1_IMG:0x8c03,COMPRESSED_RGB_ETC1_WEBGL:0x8d64,COMPRESSED_RGB_ATC_WEBGL:0x8c92,COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL:0x8c93,COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL:0x87ee,COMPRESSED_RGBA_ASTC_4X4_KHR:0x93b0,COMPRESSED_RGBA_ASTC_5X4_KHR:0x93b1,COMPRESSED_RGBA_ASTC_5X5_KHR:0x93b2,COMPRESSED_RGBA_ASTC_6X5_KHR:0x93b3,COMPRESSED_RGBA_ASTC_6X6_KHR:0x93b4,COMPRESSED_RGBA_ASTC_8X5_KHR:0x93b5,COMPRESSED_RGBA_ASTC_8X6_KHR:0x93b6,COMPRESSED_RGBA_ASTC_8X8_KHR:0x93b7,COMPRESSED_RGBA_ASTC_10X5_KHR:0x93b8,COMPRESSED_RGBA_ASTC_10X6_KHR:0x93b9,COMPRESSED_RGBA_ASTC_10X8_KHR:0x93ba,COMPRESSED_RGBA_ASTC_10X10_KHR:0x93bb,COMPRESSED_RGBA_ASTC_12X10_KHR:0x93bc,COMPRESSED_RGBA_ASTC_12X12_KHR:0x93bd,COMPRESSED_SRGB8_ALPHA8_ASTC_4X4_KHR:0x93d0,COMPRESSED_SRGB8_ALPHA8_ASTC_5X4_KHR:0x93d1,COMPRESSED_SRGB8_ALPHA8_ASTC_5X5_KHR:0x93d2,COMPRESSED_SRGB8_ALPHA8_ASTC_6X5_KHR:0x93d3,COMPRESSED_SRGB8_ALPHA8_ASTC_6X6_KHR:0x93d4,COMPRESSED_SRGB8_ALPHA8_ASTC_8X5_KHR:0x93d5,COMPRESSED_SRGB8_ALPHA8_ASTC_8X6_KHR:0x93d6,COMPRESSED_SRGB8_ALPHA8_ASTC_8X8_KHR:0x93d7,COMPRESSED_SRGB8_ALPHA8_ASTC_10X5_KHR:0x93d8,COMPRESSED_SRGB8_ALPHA8_ASTC_10X6_KHR:0x93d9,COMPRESSED_SRGB8_ALPHA8_ASTC_10X8_KHR:0x93da,COMPRESSED_SRGB8_ALPHA8_ASTC_10X10_KHR:0x93db,COMPRESSED_SRGB8_ALPHA8_ASTC_12X10_KHR:0x93dc,COMPRESSED_SRGB8_ALPHA8_ASTC_12X12_KHR:0x93dd,COMPRESSED_RED_RGTC1_EXT:0x8dbb,COMPRESSED_SIGNED_RED_RGTC1_EXT:0x8dbc,COMPRESSED_RED_GREEN_RGTC2_EXT:0x8dbd,COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:0x8dbe,COMPRESSED_SRGB_S3TC_DXT1_EXT:0x8c4c,COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:0x8c4d,COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:0x8c4e,COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:0x8c4f};var BROWSER_PREFIXES=['','WEBKIT_','MOZ_'];var WEBGL_EXTENSIONS={WEBGL_compressed_texture_s3tc:'dxt',WEBGL_compressed_texture_s3tc_srgb:'dxt-srgb',WEBGL_compressed_texture_etc1:'etc1',WEBGL_compressed_texture_etc:'etc2',WEBGL_compressed_texture_pvrtc:'pvrtc',WEBGL_compressed_texture_atc:'atc',WEBGL_compressed_texture_astc:'astc',EXT_texture_compression_rgtc:'rgtc'};var formats=null;function getSupportedGPUTextureFormats(gl){if(!formats){gl=gl||getWebGLContext()||undefined;formats=new Set();var _iterator16=_createForOfIteratorHelper(BROWSER_PREFIXES),_step16;try{for(_iterator16.s();!(_step16=_iterator16.n()).done;){var prefix=_step16.value;for(var extension in WEBGL_EXTENSIONS){if(gl&&gl.getExtension("".concat(prefix).concat(extension))){var gpuTextureFormat=WEBGL_EXTENSIONS[extension];formats.add(gpuTextureFormat);}}}}catch(err){_iterator16.e(err);}finally{_iterator16.f();}}return formats;}function getWebGLContext(){try{var _canvas6=document.createElement('canvas');return _canvas6.getContext('webgl');}catch(error){return null;}}var n,i,s,a,r,o,l,f;!function(t){t[t.NONE=0]="NONE",t[t.BASISLZ=1]="BASISLZ",t[t.ZSTD=2]="ZSTD",t[t.ZLIB=3]="ZLIB";}(n||(n={})),function(t){t[t.BASICFORMAT=0]="BASICFORMAT";}(i||(i={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.ETC1S=163]="ETC1S",t[t.UASTC=166]="UASTC";}(s||(s={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.SRGB=1]="SRGB";}(a||(a={})),function(t){t[t.UNSPECIFIED=0]="UNSPECIFIED",t[t.LINEAR=1]="LINEAR",t[t.SRGB=2]="SRGB",t[t.ITU=3]="ITU",t[t.NTSC=4]="NTSC",t[t.SLOG=5]="SLOG",t[t.SLOG2=6]="SLOG2";}(r||(r={})),function(t){t[t.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",t[t.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED";}(o||(o={})),function(t){t[t.RGB=0]="RGB",t[t.RRR=3]="RRR",t[t.GGG=4]="GGG",t[t.AAA=15]="AAA";}(l||(l={})),function(t){t[t.RGB=0]="RGB",t[t.RGBA=3]="RGBA",t[t.RRR=4]="RRR",t[t.RRRG=5]="RRRG";}(f||(f={}));var KTX2_ID=[0xab,0x4b,0x54,0x58,0x20,0x32,0x30,0xbb,0x0d,0x0a,0x1a,0x0a];function isKTX(data){var id=new Uint8Array(data);var notKTX=id.byteLength1&&_args27[1]!==undefined?_args27[1]:null;if(isEmptyObject(imagebitmapOptions)||!imagebitmapOptionsSupported){imagebitmapOptions=null;}if(!imagebitmapOptions){_context33.next=13;break;}_context33.prev=3;_context33.next=6;return createImageBitmap(blob,imagebitmapOptions);case 6:return _context33.abrupt("return",_context33.sent);case 9:_context33.prev=9;_context33.t0=_context33["catch"](3);console.warn(_context33.t0);imagebitmapOptionsSupported=false;case 13:_context33.next=15;return createImageBitmap(blob);case 15:return _context33.abrupt("return",_context33.sent);case 16:case"end":return _context33.stop();}}},_callee29,null,[[3,9]]);}));return _safeCreateImageBitmap.apply(this,arguments);}function isEmptyObject(object){for(var key in object||EMPTY_OBJECT){return false;}return true;}var BIG_ENDIAN=false;var LITTLE_ENDIAN=true;function getBinaryImageMetadata(binaryData){var dataView=toDataView(binaryData);return getPngMetadata(dataView)||getJpegMetadata(dataView)||getGifMetadata(dataView)||getBmpMetadata(dataView);}function getPngMetadata(binaryData){var dataView=toDataView(binaryData);var isPng=dataView.byteLength>=24&&dataView.getUint32(0,BIG_ENDIAN)===0x89504e47;if(!isPng){return null;}return{mimeType:'image/png',width:dataView.getUint32(16,BIG_ENDIAN),height:dataView.getUint32(20,BIG_ENDIAN)};}function getGifMetadata(binaryData){var dataView=toDataView(binaryData);var isGif=dataView.byteLength>=10&&dataView.getUint32(0,BIG_ENDIAN)===0x47494638;if(!isGif){return null;}return{mimeType:'image/gif',width:dataView.getUint16(6,LITTLE_ENDIAN),height:dataView.getUint16(8,LITTLE_ENDIAN)};}function getBmpMetadata(binaryData){var dataView=toDataView(binaryData);var isBmp=dataView.byteLength>=14&&dataView.getUint16(0,BIG_ENDIAN)===0x424d&&dataView.getUint32(2,LITTLE_ENDIAN)===dataView.byteLength;if(!isBmp){return null;}return{mimeType:'image/bmp',width:dataView.getUint32(18,LITTLE_ENDIAN),height:dataView.getUint32(22,LITTLE_ENDIAN)};}function getJpegMetadata(binaryData){var dataView=toDataView(binaryData);var isJpeg=dataView.byteLength>=3&&dataView.getUint16(0,BIG_ENDIAN)===0xffd8&&dataView.getUint8(2)===0xff;if(!isJpeg){return null;}var _getJpegMarkers=getJpegMarkers(),tableMarkers=_getJpegMarkers.tableMarkers,sofMarkers=_getJpegMarkers.sofMarkers;var i=2;while(i+9=0&&byteLength<=bufferView.byteLength);return{ArrayType:ArrayType,length:length,byteLength:byteLength};}var DEFAULT_GLTF_JSON={asset:{version:'2.0',generator:'loaders.gl'},buffers:[]};var GLTFScenegraph=/*#__PURE__*/function(){function GLTFScenegraph(gltf){_classCallCheck(this,GLTFScenegraph);_defineProperty(this,"gltf",void 0);_defineProperty(this,"sourceBuffers",void 0);_defineProperty(this,"byteLength",void 0);this.gltf=gltf||{json:_objectSpread({},DEFAULT_GLTF_JSON),buffers:[]};this.sourceBuffers=[];this.byteLength=0;if(this.gltf.buffers&&this.gltf.buffers[0]){this.byteLength=this.gltf.buffers[0].byteLength;this.sourceBuffers=[this.gltf.buffers[0]];}}_createClass(GLTFScenegraph,[{key:"json",get:function get(){return this.gltf.json;}},{key:"getApplicationData",value:function getApplicationData(key){var data=this.json[key];return data;}},{key:"getExtraData",value:function getExtraData(key){var extras=this.json.extras||{};return extras[key];}},{key:"getExtension",value:function getExtension(extensionName){var isExtension=this.getUsedExtensions().find(function(name){return name===extensionName;});var extensions=this.json.extensions||{};return isExtension?extensions[extensionName]||true:null;}},{key:"getRequiredExtension",value:function getRequiredExtension(extensionName){var isRequired=this.getRequiredExtensions().find(function(name){return name===extensionName;});return isRequired?this.getExtension(extensionName):null;}},{key:"getRequiredExtensions",value:function getRequiredExtensions(){return this.json.extensionsRequired||[];}},{key:"getUsedExtensions",value:function getUsedExtensions(){return this.json.extensionsUsed||[];}},{key:"getObjectExtension",value:function getObjectExtension(object,extensionName){var extensions=object.extensions||{};return extensions[extensionName];}},{key:"getScene",value:function getScene(index){return this.getObject('scenes',index);}},{key:"getNode",value:function getNode(index){return this.getObject('nodes',index);}},{key:"getSkin",value:function getSkin(index){return this.getObject('skins',index);}},{key:"getMesh",value:function getMesh(index){return this.getObject('meshes',index);}},{key:"getMaterial",value:function getMaterial(index){return this.getObject('materials',index);}},{key:"getAccessor",value:function getAccessor(index){return this.getObject('accessors',index);}},{key:"getTexture",value:function getTexture(index){return this.getObject('textures',index);}},{key:"getSampler",value:function getSampler(index){return this.getObject('samplers',index);}},{key:"getImage",value:function getImage(index){return this.getObject('images',index);}},{key:"getBufferView",value:function getBufferView(index){return this.getObject('bufferViews',index);}},{key:"getBuffer",value:function getBuffer(index){return this.getObject('buffers',index);}},{key:"getObject",value:function getObject(array,index){if(_typeof(index)==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){throw new Error("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}},{key:"getTypedArrayForBufferView",value:function getTypedArrayForBufferView(bufferView){bufferView=this.getBufferView(bufferView);var bufferIndex=bufferView.buffer;var binChunk=this.gltf.buffers[bufferIndex];assert$1(binChunk);var byteOffset=(bufferView.byteOffset||0)+binChunk.byteOffset;return new Uint8Array(binChunk.arrayBuffer,byteOffset,bufferView.byteLength);}},{key:"getTypedArrayForAccessor",value:function getTypedArrayForAccessor(accessor){accessor=this.getAccessor(accessor);var bufferView=this.getBufferView(accessor.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var _getAccessorArrayType=getAccessorArrayTypeAndLength(accessor,bufferView),ArrayType=_getAccessorArrayType.ArrayType,length=_getAccessorArrayType.length;var byteOffset=bufferView.byteOffset+accessor.byteOffset;return new ArrayType(arrayBuffer,byteOffset,length);}},{key:"getTypedArrayForImageData",value:function getTypedArrayForImageData(image){image=this.getAccessor(image);var bufferView=this.getBufferView(image.bufferView);var buffer=this.getBuffer(bufferView.buffer);var arrayBuffer=buffer.data;var byteOffset=bufferView.byteOffset||0;return new Uint8Array(arrayBuffer,byteOffset,bufferView.byteLength);}},{key:"addApplicationData",value:function addApplicationData(key,data){this.json[key]=data;return this;}},{key:"addExtraData",value:function addExtraData(key,data){this.json.extras=this.json.extras||{};this.json.extras[key]=data;return this;}},{key:"addObjectExtension",value:function addObjectExtension(object,extensionName,data){object.extensions=object.extensions||{};object.extensions[extensionName]=data;this.registerUsedExtension(extensionName);return this;}},{key:"setObjectExtension",value:function setObjectExtension(object,extensionName,data){var extensions=object.extensions||{};extensions[extensionName]=data;}},{key:"removeObjectExtension",value:function removeObjectExtension(object,extensionName){var extensions=object.extensions||{};var extension=extensions[extensionName];delete extensions[extensionName];return extension;}},{key:"addExtension",value:function addExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.json.extensions=this.json.extensions||{};this.json.extensions[extensionName]=extensionData;this.registerUsedExtension(extensionName);return extensionData;}},{key:"addRequiredExtension",value:function addRequiredExtension(extensionName){var extensionData=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};assert$1(extensionData);this.addExtension(extensionName,extensionData);this.registerRequiredExtension(extensionName);return extensionData;}},{key:"registerUsedExtension",value:function registerUsedExtension(extensionName){this.json.extensionsUsed=this.json.extensionsUsed||[];if(!this.json.extensionsUsed.find(function(ext){return ext===extensionName;})){this.json.extensionsUsed.push(extensionName);}}},{key:"registerRequiredExtension",value:function registerRequiredExtension(extensionName){this.registerUsedExtension(extensionName);this.json.extensionsRequired=this.json.extensionsRequired||[];if(!this.json.extensionsRequired.find(function(ext){return ext===extensionName;})){this.json.extensionsRequired.push(extensionName);}}},{key:"removeExtension",value:function removeExtension(extensionName){if(this.json.extensionsRequired){this._removeStringFromArray(this.json.extensionsRequired,extensionName);}if(this.json.extensionsUsed){this._removeStringFromArray(this.json.extensionsUsed,extensionName);}if(this.json.extensions){delete this.json.extensions[extensionName];}}},{key:"setDefaultScene",value:function setDefaultScene(sceneIndex){this.json.scene=sceneIndex;}},{key:"addScene",value:function addScene(scene){var nodeIndices=scene.nodeIndices;this.json.scenes=this.json.scenes||[];this.json.scenes.push({nodes:nodeIndices});return this.json.scenes.length-1;}},{key:"addNode",value:function addNode(node){var meshIndex=node.meshIndex,matrix=node.matrix;this.json.nodes=this.json.nodes||[];var nodeData={mesh:meshIndex};if(matrix){nodeData.matrix=matrix;}this.json.nodes.push(nodeData);return this.json.nodes.length-1;}},{key:"addMesh",value:function addMesh(mesh){var attributes=mesh.attributes,indices=mesh.indices,material=mesh.material,_mesh$mode=mesh.mode,mode=_mesh$mode===void 0?4:_mesh$mode;var accessors=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessors,mode:mode}]};if(indices){var indicesAccessor=this._addIndices(indices);glTFMesh.primitives[0].indices=indicesAccessor;}if(Number.isFinite(material)){glTFMesh.primitives[0].material=material;}this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}},{key:"addPointCloud",value:function addPointCloud(attributes){var accessorIndices=this._addAttributes(attributes);var glTFMesh={primitives:[{attributes:accessorIndices,mode:0}]};this.json.meshes=this.json.meshes||[];this.json.meshes.push(glTFMesh);return this.json.meshes.length-1;}},{key:"addImage",value:function addImage(imageData,mimeTypeOpt){var metadata=getBinaryImageMetadata(imageData);var mimeType=mimeTypeOpt||(metadata===null||metadata===void 0?void 0:metadata.mimeType);var bufferViewIndex=this.addBufferView(imageData);var glTFImage={bufferView:bufferViewIndex,mimeType:mimeType};this.json.images=this.json.images||[];this.json.images.push(glTFImage);return this.json.images.length-1;}},{key:"addBufferView",value:function addBufferView(buffer){var byteLength=buffer.byteLength;assert$1(Number.isFinite(byteLength));this.sourceBuffers=this.sourceBuffers||[];this.sourceBuffers.push(buffer);var glTFBufferView={buffer:0,byteOffset:this.byteLength,byteLength:byteLength};this.byteLength+=padToNBytes(byteLength,4);this.json.bufferViews=this.json.bufferViews||[];this.json.bufferViews.push(glTFBufferView);return this.json.bufferViews.length-1;}},{key:"addAccessor",value:function addAccessor(bufferViewIndex,accessor){var glTFAccessor={bufferView:bufferViewIndex,type:getAccessorTypeFromSize(accessor.size),componentType:accessor.componentType,count:accessor.count,max:accessor.max,min:accessor.min};this.json.accessors=this.json.accessors||[];this.json.accessors.push(glTFAccessor);return this.json.accessors.length-1;}},{key:"addBinaryBuffer",value:function addBinaryBuffer(sourceBuffer){var accessor=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{size:3};var bufferViewIndex=this.addBufferView(sourceBuffer);var minMax={min:accessor.min,max:accessor.max};if(!minMax.min||!minMax.max){minMax=this._getAccessorMinMax(sourceBuffer,accessor.size);}var accessorDefaults={size:accessor.size,componentType:getComponentTypeFromArray(sourceBuffer),count:Math.round(sourceBuffer.length/accessor.size),min:minMax.min,max:minMax.max};return this.addAccessor(bufferViewIndex,Object.assign(accessorDefaults,accessor));}},{key:"addTexture",value:function addTexture(texture){var imageIndex=texture.imageIndex;var glTFTexture={source:imageIndex};this.json.textures=this.json.textures||[];this.json.textures.push(glTFTexture);return this.json.textures.length-1;}},{key:"addMaterial",value:function addMaterial(pbrMaterialInfo){this.json.materials=this.json.materials||[];this.json.materials.push(pbrMaterialInfo);return this.json.materials.length-1;}},{key:"createBinaryChunk",value:function createBinaryChunk(){var _this$json,_this$json$buffers;this.gltf.buffers=[];var totalByteLength=this.byteLength;var arrayBuffer=new ArrayBuffer(totalByteLength);var targetArray=new Uint8Array(arrayBuffer);var dstByteOffset=0;var _iterator17=_createForOfIteratorHelper(this.sourceBuffers||[]),_step17;try{for(_iterator17.s();!(_step17=_iterator17.n()).done;){var sourceBuffer=_step17.value;dstByteOffset=copyToArray(sourceBuffer,targetArray,dstByteOffset);}}catch(err){_iterator17.e(err);}finally{_iterator17.f();}if((_this$json=this.json)!==null&&_this$json!==void 0&&(_this$json$buffers=_this$json.buffers)!==null&&_this$json$buffers!==void 0&&_this$json$buffers[0]){this.json.buffers[0].byteLength=totalByteLength;}else{this.json.buffers=[{byteLength:totalByteLength}];}this.gltf.binary=arrayBuffer;this.sourceBuffers=[arrayBuffer];}},{key:"_removeStringFromArray",value:function _removeStringFromArray(array,string){var found=true;while(found){var index=array.indexOf(string);if(index>-1){array.splice(index,1);}else{found=false;}}}},{key:"_addAttributes",value:function _addAttributes(){var attributes=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var result={};for(var attributeKey in attributes){var attributeData=attributes[attributeKey];var attrName=this._getGltfAttributeName(attributeKey);var accessor=this.addBinaryBuffer(attributeData.value,attributeData);result[attrName]=accessor;}return result;}},{key:"_addIndices",value:function _addIndices(indices){return this.addBinaryBuffer(indices,{size:1});}},{key:"_getGltfAttributeName",value:function _getGltfAttributeName(attributeName){switch(attributeName.toLowerCase()){case'position':case'positions':case'vertices':return'POSITION';case'normal':case'normals':return'NORMAL';case'color':case'colors':return'COLOR_0';case'texcoord':case'texcoords':return'TEXCOORD_0';default:return attributeName;}}},{key:"_getAccessorMinMax",value:function _getAccessorMinMax(buffer,size){var result={min:null,max:null};if(buffer.length5&&_args30[5]!==undefined?_args30[5]:'NONE';_context36.next=3;return loadWasmInstance();case 3:instance=_context36.sent;decode$5(instance,instance.exports[DECODERS[mode]],target,count,size,source,instance.exports[FILTERS[filter||'NONE']]);case 5:case"end":return _context36.stop();}}},_callee32);}));return _meshoptDecodeGltfBuffer.apply(this,arguments);}var wasmPromise;function loadWasmInstance(){return _loadWasmInstance.apply(this,arguments);}function _loadWasmInstance(){_loadWasmInstance=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee33(){return _regeneratorRuntime().wrap(function _callee33$(_context37){while(1){switch(_context37.prev=_context37.next){case 0:if(!wasmPromise){wasmPromise=loadWasmModule();}return _context37.abrupt("return",wasmPromise);case 2:case"end":return _context37.stop();}}},_callee33);}));return _loadWasmInstance.apply(this,arguments);}function loadWasmModule(){return _loadWasmModule.apply(this,arguments);}function _loadWasmModule(){_loadWasmModule=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee34(){var wasm,result;return _regeneratorRuntime().wrap(function _callee34$(_context38){while(1){switch(_context38.prev=_context38.next){case 0:wasm=wasm_base;if(WebAssembly.validate(detector)){wasm=wasm_simd;console.log('Warning: meshopt_decoder is using experimental SIMD support');}_context38.next=4;return WebAssembly.instantiate(unpack(wasm),{});case 4:result=_context38.sent;_context38.next=7;return result.instance.exports.__wasm_call_ctors();case 7:return _context38.abrupt("return",result.instance);case 8:case"end":return _context38.stop();}}},_callee34);}));return _loadWasmModule.apply(this,arguments);}function unpack(data){var result=new Uint8Array(data.length);for(var _i501=0;_i50196?ch-71:ch>64?ch-65:ch>47?ch+4:ch>46?63:62;}var write=0;for(var _i502=0;_i502maxX?x:maxX;maxY=y>maxY?y:maxY;maxZ=_z4>maxZ?_z4:maxZ;}return[[minX,minY,minZ],[maxX,maxY,maxZ]];}function assert(condition,message){if(!condition){throw new Error(message||'loader assertion failed.');}}var Schema=/*#__PURE__*/function(){function Schema(fields,metadata){_classCallCheck(this,Schema);_defineProperty(this,"fields",void 0);_defineProperty(this,"metadata",void 0);assert(Array.isArray(fields));checkNames(fields);this.fields=fields;this.metadata=metadata||new Map();}_createClass(Schema,[{key:"compareTo",value:function compareTo(other){if(this.metadata!==other.metadata){return false;}if(this.fields.length!==other.fields.length){return false;}for(var _i504=0;_i5042&&arguments[2]!==undefined?arguments[2]:false;var metadata=arguments.length>3&&arguments[3]!==undefined?arguments[3]:new Map();_classCallCheck(this,Field);_defineProperty(this,"name",void 0);_defineProperty(this,"type",void 0);_defineProperty(this,"nullable",void 0);_defineProperty(this,"metadata",void 0);this.name=name;this.type=type;this.nullable=nullable;this.metadata=metadata;}_createClass(Field,[{key:"typeId",get:function get(){return this.type&&this.type.typeId;}},{key:"clone",value:function clone(){return new Field(this.name,this.type,this.nullable,this.metadata);}},{key:"compareTo",value:function compareTo(other){return this.name===other.name&&this.type===other.type&&this.nullable===other.nullable&&this.metadata===other.metadata;}},{key:"toString",value:function toString(){return"".concat(this.type).concat(this.nullable?', nullable':'').concat(this.metadata?", metadata: ".concat(this.metadata):'');}}]);return Field;}();var Type;(function(Type){Type[Type["NONE"]=0]="NONE";Type[Type["Null"]=1]="Null";Type[Type["Int"]=2]="Int";Type[Type["Float"]=3]="Float";Type[Type["Binary"]=4]="Binary";Type[Type["Utf8"]=5]="Utf8";Type[Type["Bool"]=6]="Bool";Type[Type["Decimal"]=7]="Decimal";Type[Type["Date"]=8]="Date";Type[Type["Time"]=9]="Time";Type[Type["Timestamp"]=10]="Timestamp";Type[Type["Interval"]=11]="Interval";Type[Type["List"]=12]="List";Type[Type["Struct"]=13]="Struct";Type[Type["Union"]=14]="Union";Type[Type["FixedSizeBinary"]=15]="FixedSizeBinary";Type[Type["FixedSizeList"]=16]="FixedSizeList";Type[Type["Map"]=17]="Map";Type[Type["Dictionary"]=-1]="Dictionary";Type[Type["Int8"]=-2]="Int8";Type[Type["Int16"]=-3]="Int16";Type[Type["Int32"]=-4]="Int32";Type[Type["Int64"]=-5]="Int64";Type[Type["Uint8"]=-6]="Uint8";Type[Type["Uint16"]=-7]="Uint16";Type[Type["Uint32"]=-8]="Uint32";Type[Type["Uint64"]=-9]="Uint64";Type[Type["Float16"]=-10]="Float16";Type[Type["Float32"]=-11]="Float32";Type[Type["Float64"]=-12]="Float64";Type[Type["DateDay"]=-13]="DateDay";Type[Type["DateMillisecond"]=-14]="DateMillisecond";Type[Type["TimestampSecond"]=-15]="TimestampSecond";Type[Type["TimestampMillisecond"]=-16]="TimestampMillisecond";Type[Type["TimestampMicrosecond"]=-17]="TimestampMicrosecond";Type[Type["TimestampNanosecond"]=-18]="TimestampNanosecond";Type[Type["TimeSecond"]=-19]="TimeSecond";Type[Type["TimeMillisecond"]=-20]="TimeMillisecond";Type[Type["TimeMicrosecond"]=-21]="TimeMicrosecond";Type[Type["TimeNanosecond"]=-22]="TimeNanosecond";Type[Type["DenseUnion"]=-23]="DenseUnion";Type[Type["SparseUnion"]=-24]="SparseUnion";Type[Type["IntervalDayTime"]=-25]="IntervalDayTime";Type[Type["IntervalYearMonth"]=-26]="IntervalYearMonth";})(Type||(Type={}));var _Symbol$toStringTag,_Symbol$toStringTag2,_Symbol$toStringTag7;var DataType=/*#__PURE__*/function(){function DataType(){_classCallCheck(this,DataType);}_createClass(DataType,[{key:"typeId",get:function get(){return Type.NONE;}},{key:"compareTo",value:function compareTo(other){return this===other;}}],[{key:"isNull",value:function isNull(x){return x&&x.typeId===Type.Null;}},{key:"isInt",value:function isInt(x){return x&&x.typeId===Type.Int;}},{key:"isFloat",value:function isFloat(x){return x&&x.typeId===Type.Float;}},{key:"isBinary",value:function isBinary(x){return x&&x.typeId===Type.Binary;}},{key:"isUtf8",value:function isUtf8(x){return x&&x.typeId===Type.Utf8;}},{key:"isBool",value:function isBool(x){return x&&x.typeId===Type.Bool;}},{key:"isDecimal",value:function isDecimal(x){return x&&x.typeId===Type.Decimal;}},{key:"isDate",value:function isDate(x){return x&&x.typeId===Type.Date;}},{key:"isTime",value:function isTime(x){return x&&x.typeId===Type.Time;}},{key:"isTimestamp",value:function isTimestamp(x){return x&&x.typeId===Type.Timestamp;}},{key:"isInterval",value:function isInterval(x){return x&&x.typeId===Type.Interval;}},{key:"isList",value:function isList(x){return x&&x.typeId===Type.List;}},{key:"isStruct",value:function isStruct(x){return x&&x.typeId===Type.Struct;}},{key:"isUnion",value:function isUnion(x){return x&&x.typeId===Type.Union;}},{key:"isFixedSizeBinary",value:function isFixedSizeBinary(x){return x&&x.typeId===Type.FixedSizeBinary;}},{key:"isFixedSizeList",value:function isFixedSizeList(x){return x&&x.typeId===Type.FixedSizeList;}},{key:"isMap",value:function isMap(x){return x&&x.typeId===Type.Map;}},{key:"isDictionary",value:function isDictionary(x){return x&&x.typeId===Type.Dictionary;}}]);return DataType;}();_Symbol$toStringTag=Symbol.toStringTag;var Int=/*#__PURE__*/function(_DataType,_Symbol$toStringTag3){_inherits(Int,_DataType);var _super140=_createSuper(Int);function Int(isSigned,bitWidth){var _this117;_classCallCheck(this,Int);_this117=_super140.call(this);_defineProperty(_assertThisInitialized(_this117),"isSigned",void 0);_defineProperty(_assertThisInitialized(_this117),"bitWidth",void 0);_this117.isSigned=isSigned;_this117.bitWidth=bitWidth;return _this117;}_createClass(Int,[{key:"typeId",get:function get(){return Type.Int;}},{key:_Symbol$toStringTag3,get:function get(){return'Int';}},{key:"toString",value:function toString(){return"".concat(this.isSigned?'I':'Ui',"nt").concat(this.bitWidth);}}]);return Int;}(DataType,_Symbol$toStringTag);var Int8=/*#__PURE__*/function(_Int){_inherits(Int8,_Int);var _super141=_createSuper(Int8);function Int8(){_classCallCheck(this,Int8);return _super141.call(this,true,8);}return _createClass(Int8);}(Int);var Int16=/*#__PURE__*/function(_Int2){_inherits(Int16,_Int2);var _super142=_createSuper(Int16);function Int16(){_classCallCheck(this,Int16);return _super142.call(this,true,16);}return _createClass(Int16);}(Int);var Int32=/*#__PURE__*/function(_Int3){_inherits(Int32,_Int3);var _super143=_createSuper(Int32);function Int32(){_classCallCheck(this,Int32);return _super143.call(this,true,32);}return _createClass(Int32);}(Int);var Uint8=/*#__PURE__*/function(_Int4){_inherits(Uint8,_Int4);var _super144=_createSuper(Uint8);function Uint8(){_classCallCheck(this,Uint8);return _super144.call(this,false,8);}return _createClass(Uint8);}(Int);var Uint16=/*#__PURE__*/function(_Int5){_inherits(Uint16,_Int5);var _super145=_createSuper(Uint16);function Uint16(){_classCallCheck(this,Uint16);return _super145.call(this,false,16);}return _createClass(Uint16);}(Int);var Uint32=/*#__PURE__*/function(_Int6){_inherits(Uint32,_Int6);var _super146=_createSuper(Uint32);function Uint32(){_classCallCheck(this,Uint32);return _super146.call(this,false,32);}return _createClass(Uint32);}(Int);var Precision={HALF:16,SINGLE:32,DOUBLE:64};_Symbol$toStringTag2=Symbol.toStringTag;var Float=/*#__PURE__*/function(_DataType2,_Symbol$toStringTag4){_inherits(Float,_DataType2);var _super147=_createSuper(Float);function Float(precision){var _this118;_classCallCheck(this,Float);_this118=_super147.call(this);_defineProperty(_assertThisInitialized(_this118),"precision",void 0);_this118.precision=precision;return _this118;}_createClass(Float,[{key:"typeId",get:function get(){return Type.Float;}},{key:_Symbol$toStringTag4,get:function get(){return'Float';}},{key:"toString",value:function toString(){return"Float".concat(this.precision);}}]);return Float;}(DataType,_Symbol$toStringTag2);var Float32=/*#__PURE__*/function(_Float){_inherits(Float32,_Float);var _super148=_createSuper(Float32);function Float32(){_classCallCheck(this,Float32);return _super148.call(this,Precision.SINGLE);}return _createClass(Float32);}(Float);var Float64=/*#__PURE__*/function(_Float2){_inherits(Float64,_Float2);var _super149=_createSuper(Float64);function Float64(){_classCallCheck(this,Float64);return _super149.call(this,Precision.DOUBLE);}return _createClass(Float64);}(Float);_Symbol$toStringTag7=Symbol.toStringTag;var FixedSizeList=/*#__PURE__*/function(_DataType3,_Symbol$toStringTag5){_inherits(FixedSizeList,_DataType3);var _super150=_createSuper(FixedSizeList);function FixedSizeList(listSize,child){var _this119;_classCallCheck(this,FixedSizeList);_this119=_super150.call(this);_defineProperty(_assertThisInitialized(_this119),"listSize",void 0);_defineProperty(_assertThisInitialized(_this119),"children",void 0);_this119.listSize=listSize;_this119.children=[child];return _this119;}_createClass(FixedSizeList,[{key:"typeId",get:function get(){return Type.FixedSizeList;}},{key:"valueType",get:function get(){return this.children[0].type;}},{key:"valueField",get:function get(){return this.children[0];}},{key:_Symbol$toStringTag5,get:function get(){return'FixedSizeList';}},{key:"toString",value:function toString(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">");}}]);return FixedSizeList;}(DataType,_Symbol$toStringTag7);function getArrowTypeFromTypedArray(array){switch(array.constructor){case Int8Array:return new Int8();case Uint8Array:return new Uint8();case Int16Array:return new Int16();case Uint16Array:return new Uint16();case Int32Array:return new Int32();case Uint32Array:return new Uint32();case Float32Array:return new Float32();case Float64Array:return new Float64();default:throw new Error('array type not supported');}}function deduceMeshField(attributeName,attribute,optionalMetadata){var type=getArrowTypeFromTypedArray(attribute.value);var metadata=optionalMetadata?optionalMetadata:makeMeshAttributeMetadata(attribute);var field=new Field(attributeName,new FixedSizeList(attribute.size,new Field('value',type)),false,metadata);return field;}function makeMeshAttributeMetadata(attribute){var result=new Map();if('byteOffset'in attribute){result.set('byteOffset',attribute.byteOffset.toString(10));}if('byteStride'in attribute){result.set('byteStride',attribute.byteStride.toString(10));}if('normalized'in attribute){result.set('normalized',attribute.normalized.toString());}return result;}function getDracoSchema(attributes,loaderData,indices){var metadataMap=makeMetadata(loaderData.metadata);var fields=[];var namedLoaderDataAttributes=transformAttributesLoaderData(loaderData.attributes);for(var attributeName in attributes){var attribute=attributes[attributeName];var field=getArrowFieldFromAttribute(attributeName,attribute,namedLoaderDataAttributes[attributeName]);fields.push(field);}if(indices){var indicesField=getArrowFieldFromAttribute('indices',indices);fields.push(indicesField);}return new Schema(fields,metadataMap);}function transformAttributesLoaderData(loaderData){var result={};for(var key in loaderData){var dracoAttribute=loaderData[key];result[dracoAttribute.name||'undefined']=dracoAttribute;}return result;}function getArrowFieldFromAttribute(attributeName,attribute,loaderData){var metadataMap=loaderData?makeMetadata(loaderData.metadata):undefined;var field=deduceMeshField(attributeName,attribute,metadataMap);return field;}function makeMetadata(metadata){var metadataMap=new Map();for(var key in metadata){metadataMap.set("".concat(key,".string"),JSON.stringify(metadata[key]));}return metadataMap;}var DRACO_TO_GLTF_ATTRIBUTE_NAME_MAP={POSITION:'POSITION',NORMAL:'NORMAL',COLOR:'COLOR_0',TEX_COORD:'TEXCOORD_0'};var DRACO_DATA_TYPE_TO_TYPED_ARRAY_MAP={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array};var INDEX_ITEM_SIZE=4;var DracoParser=/*#__PURE__*/function(){function DracoParser(draco){_classCallCheck(this,DracoParser);_defineProperty(this,"draco",void 0);_defineProperty(this,"decoder",void 0);_defineProperty(this,"metadataQuerier",void 0);this.draco=draco;this.decoder=new this.draco.Decoder();this.metadataQuerier=new this.draco.MetadataQuerier();}_createClass(DracoParser,[{key:"destroy",value:function destroy(){this.draco.destroy(this.decoder);this.draco.destroy(this.metadataQuerier);}},{key:"parseSync",value:function parseSync(arrayBuffer){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var buffer=new this.draco.DecoderBuffer();buffer.Init(new Int8Array(arrayBuffer),arrayBuffer.byteLength);this._disableAttributeTransforms(options);var geometry_type=this.decoder.GetEncodedGeometryType(buffer);var dracoGeometry=geometry_type===this.draco.TRIANGULAR_MESH?new this.draco.Mesh():new this.draco.PointCloud();try{var dracoStatus;switch(geometry_type){case this.draco.TRIANGULAR_MESH:dracoStatus=this.decoder.DecodeBufferToMesh(buffer,dracoGeometry);break;case this.draco.POINT_CLOUD:dracoStatus=this.decoder.DecodeBufferToPointCloud(buffer,dracoGeometry);break;default:throw new Error('DRACO: Unknown geometry type.');}if(!dracoStatus.ok()||!dracoGeometry.ptr){var message="DRACO decompression failed: ".concat(dracoStatus.error_msg());throw new Error(message);}var loaderData=this._getDracoLoaderData(dracoGeometry,geometry_type,options);var geometry=this._getMeshData(dracoGeometry,loaderData,options);var boundingBox=getMeshBoundingBox(geometry.attributes);var schema=getDracoSchema(geometry.attributes,loaderData,geometry.indices);var data=_objectSpread(_objectSpread({loader:'draco',loaderData:loaderData,header:{vertexCount:dracoGeometry.num_points(),boundingBox:boundingBox}},geometry),{},{schema:schema});return data;}finally{this.draco.destroy(buffer);if(dracoGeometry){this.draco.destroy(dracoGeometry);}}}},{key:"_getDracoLoaderData",value:function _getDracoLoaderData(dracoGeometry,geometry_type,options){var metadata=this._getTopLevelMetadata(dracoGeometry);var attributes=this._getDracoAttributes(dracoGeometry,options);return{geometry_type:geometry_type,num_attributes:dracoGeometry.num_attributes(),num_points:dracoGeometry.num_points(),num_faces:dracoGeometry instanceof this.draco.Mesh?dracoGeometry.num_faces():0,metadata:metadata,attributes:attributes};}},{key:"_getDracoAttributes",value:function _getDracoAttributes(dracoGeometry,options){var dracoAttributes={};for(var attributeId=0;attributeId2&&arguments[2]!==undefined?arguments[2]:false;if(!array){return null;}if(Array.isArray(array)){return new ArrayType(array);}if(convertTypedArrays&&!(array instanceof ArrayType)){return new ArrayType(array);}return array;}var KHR_DRACO_MESH_COMPRESSION='KHR_draco_mesh_compression';var name$3=KHR_DRACO_MESH_COMPRESSION;function preprocess$1(gltfData,options,context){var scenegraph=new GLTFScenegraph(gltfData);var _iterator25=_createForOfIteratorHelper(makeMeshPrimitiveIterator(scenegraph)),_step25;try{for(_iterator25.s();!(_step25=_iterator25.n()).done;){var _primitive=_step25.value;if(scenegraph.getObjectExtension(_primitive,KHR_DRACO_MESH_COMPRESSION));}}catch(err){_iterator25.e(err);}finally{_iterator25.f();}}function decode$3(_x72,_x73,_x74){return _decode$2.apply(this,arguments);}function _decode$2(){_decode$2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee40(gltfData,options,context){var _options$gltf,scenegraph,promises,_iterator48,_step48,_primitive5;return _regeneratorRuntime().wrap(function _callee40$(_context44){while(1){switch(_context44.prev=_context44.next){case 0:if(options!==null&&options!==void 0&&(_options$gltf=options.gltf)!==null&&_options$gltf!==void 0&&_options$gltf.decompressMeshes){_context44.next=2;break;}return _context44.abrupt("return");case 2:scenegraph=new GLTFScenegraph(gltfData);promises=[];_iterator48=_createForOfIteratorHelper(makeMeshPrimitiveIterator(scenegraph));try{for(_iterator48.s();!(_step48=_iterator48.n()).done;){_primitive5=_step48.value;if(scenegraph.getObjectExtension(_primitive5,KHR_DRACO_MESH_COMPRESSION)){promises.push(decompressPrimitive(scenegraph,_primitive5,options,context));}}}catch(err){_iterator48.e(err);}finally{_iterator48.f();}_context44.next=8;return Promise.all(promises);case 8:scenegraph.removeExtension(KHR_DRACO_MESH_COMPRESSION);case 9:case"end":return _context44.stop();}}},_callee40);}));return _decode$2.apply(this,arguments);}function encode$3(gltfData){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var scenegraph=new GLTFScenegraph(gltfData);var _iterator26=_createForOfIteratorHelper(scenegraph.json.meshes||[]),_step26;try{for(_iterator26.s();!(_step26=_iterator26.n()).done;){var _mesh3=_step26.value;compressMesh(_mesh3);scenegraph.addRequiredExtension(KHR_DRACO_MESH_COMPRESSION);}}catch(err){_iterator26.e(err);}finally{_iterator26.f();}}function decompressPrimitive(_x75,_x76,_x77,_x78){return _decompressPrimitive.apply(this,arguments);}function _decompressPrimitive(){_decompressPrimitive=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee41(scenegraph,primitive,options,context){var dracoExtension,buffer,bufferCopy,parse,dracoOptions,decodedData,decodedAttributes,_i603,_Object$entries5,_Object$entries5$_i,attributeName,decodedAttribute,accessorIndex,accessor;return _regeneratorRuntime().wrap(function _callee41$(_context45){while(1){switch(_context45.prev=_context45.next){case 0:dracoExtension=scenegraph.getObjectExtension(primitive,KHR_DRACO_MESH_COMPRESSION);if(dracoExtension){_context45.next=3;break;}return _context45.abrupt("return");case 3:buffer=scenegraph.getTypedArrayForBufferView(dracoExtension.bufferView);bufferCopy=sliceArrayBuffer(buffer.buffer,buffer.byteOffset);parse=context.parse;dracoOptions=_objectSpread({},options);delete dracoOptions['3d-tiles'];_context45.next=10;return parse(bufferCopy,DracoLoader,dracoOptions,context);case 10:decodedData=_context45.sent;decodedAttributes=getGLTFAccessors(decodedData.attributes);for(_i603=0,_Object$entries5=Object.entries(decodedAttributes);_i603<_Object$entries5.length;_i603++){_Object$entries5$_i=_slicedToArray(_Object$entries5[_i603],2),attributeName=_Object$entries5$_i[0],decodedAttribute=_Object$entries5$_i[1];if(attributeName in primitive.attributes){accessorIndex=primitive.attributes[attributeName];accessor=scenegraph.getAccessor(accessorIndex);if(accessor!==null&&accessor!==void 0&&accessor.min&&accessor!==null&&accessor!==void 0&&accessor.max){decodedAttribute.min=accessor.min;decodedAttribute.max=accessor.max;}}}primitive.attributes=decodedAttributes;if(decodedData.indices){primitive.indices=getGLTFAccessor(decodedData.indices);}checkPrimitive(primitive);case 16:case"end":return _context45.stop();}}},_callee41);}));return _decompressPrimitive.apply(this,arguments);}function compressMesh(attributes,indices){var mode=arguments.length>2&&arguments[2]!==undefined?arguments[2]:4;var options=arguments.length>3?arguments[3]:undefined;var context=arguments.length>4?arguments[4]:undefined;var _context$parseSync;if(!options.DracoWriter){throw new Error('options.gltf.DracoWriter not provided');}var compressedData=options.DracoWriter.encodeSync({attributes:attributes});var decodedData=context===null||context===void 0?void 0:(_context$parseSync=context.parseSync)===null||_context$parseSync===void 0?void 0:_context$parseSync.call(context,{attributes:attributes});var fauxAccessors=options._addFauxAttributes(decodedData.attributes);var bufferViewIndex=options.addBufferView(compressedData);var glTFMesh={primitives:[{attributes:fauxAccessors,mode:mode,extensions:_defineProperty2({},KHR_DRACO_MESH_COMPRESSION,{bufferView:bufferViewIndex,attributes:fauxAccessors})}]};return glTFMesh;}function checkPrimitive(primitive){if(!primitive.attributes&&Object.keys(primitive.attributes).length>0){throw new Error('glTF: Empty primitive detected: Draco decompression failure?');}}function makeMeshPrimitiveIterator(scenegraph){var _iterator27,_step27,_mesh4,_iterator28,_step28,_primitive2;return _regeneratorRuntime().wrap(function makeMeshPrimitiveIterator$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_iterator27=_createForOfIteratorHelper(scenegraph.json.meshes||[]);_context10.prev=1;_iterator27.s();case 3:if((_step27=_iterator27.n()).done){_context10.next=24;break;}_mesh4=_step27.value;_iterator28=_createForOfIteratorHelper(_mesh4.primitives);_context10.prev=6;_iterator28.s();case 8:if((_step28=_iterator28.n()).done){_context10.next=14;break;}_primitive2=_step28.value;_context10.next=12;return _primitive2;case 12:_context10.next=8;break;case 14:_context10.next=19;break;case 16:_context10.prev=16;_context10.t0=_context10["catch"](6);_iterator28.e(_context10.t0);case 19:_context10.prev=19;_iterator28.f();return _context10.finish(19);case 22:_context10.next=3;break;case 24:_context10.next=29;break;case 26:_context10.prev=26;_context10.t1=_context10["catch"](1);_iterator27.e(_context10.t1);case 29:_context10.prev=29;_iterator27.f();return _context10.finish(29);case 32:case"end":return _context10.stop();}}},_marked3,null,[[1,26,29,32],[6,16,19,22]]);}var KHR_draco_mesh_compression=/*#__PURE__*/Object.freeze({__proto__:null,name:name$3,preprocess:preprocess$1,decode:decode$3,encode:encode$3});var KHR_LIGHTS_PUNCTUAL='KHR_lights_punctual';var name$2=KHR_LIGHTS_PUNCTUAL;function decode$2(_x79){return _decode$3.apply(this,arguments);}function _decode$3(){_decode$3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee42(gltfData){var gltfScenegraph,json,extension,_iterator49,_step49,_node12,nodeExtension;return _regeneratorRuntime().wrap(function _callee42$(_context46){while(1){switch(_context46.prev=_context46.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;extension=gltfScenegraph.getExtension(KHR_LIGHTS_PUNCTUAL);if(extension){gltfScenegraph.json.lights=extension.lights;gltfScenegraph.removeExtension(KHR_LIGHTS_PUNCTUAL);}_iterator49=_createForOfIteratorHelper(json.nodes||[]);try{for(_iterator49.s();!(_step49=_iterator49.n()).done;){_node12=_step49.value;nodeExtension=gltfScenegraph.getObjectExtension(_node12,KHR_LIGHTS_PUNCTUAL);if(nodeExtension){_node12.light=nodeExtension.light;}gltfScenegraph.removeObjectExtension(_node12,KHR_LIGHTS_PUNCTUAL);}}catch(err){_iterator49.e(err);}finally{_iterator49.f();}case 6:case"end":return _context46.stop();}}},_callee42);}));return _decode$3.apply(this,arguments);}function encode$2(_x80){return _encode$.apply(this,arguments);}function _encode$(){_encode$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee43(gltfData){var gltfScenegraph,json,extension,_iterator50,_step50,light,_node13;return _regeneratorRuntime().wrap(function _callee43$(_context47){while(1){switch(_context47.prev=_context47.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;if(json.lights){extension=gltfScenegraph.addExtension(KHR_LIGHTS_PUNCTUAL);assert$1(!extension.lights);extension.lights=json.lights;delete json.lights;}if(gltfScenegraph.json.lights){_iterator50=_createForOfIteratorHelper(gltfScenegraph.json.lights);try{for(_iterator50.s();!(_step50=_iterator50.n()).done;){light=_step50.value;_node13=light.node;gltfScenegraph.addObjectExtension(_node13,KHR_LIGHTS_PUNCTUAL,light);}}catch(err){_iterator50.e(err);}finally{_iterator50.f();}delete gltfScenegraph.json.lights;}case 4:case"end":return _context47.stop();}}},_callee43);}));return _encode$.apply(this,arguments);}var KHR_lights_punctual=/*#__PURE__*/Object.freeze({__proto__:null,name:name$2,decode:decode$2,encode:encode$2});var KHR_MATERIALS_UNLIT='KHR_materials_unlit';var name$1=KHR_MATERIALS_UNLIT;function decode$1(_x81){return _decode$4.apply(this,arguments);}function _decode$4(){_decode$4=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee44(gltfData){var gltfScenegraph,json,_iterator51,_step51,material,extension;return _regeneratorRuntime().wrap(function _callee44$(_context48){while(1){switch(_context48.prev=_context48.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;gltfScenegraph.removeExtension(KHR_MATERIALS_UNLIT);_iterator51=_createForOfIteratorHelper(json.materials||[]);try{for(_iterator51.s();!(_step51=_iterator51.n()).done;){material=_step51.value;extension=material.extensions&&material.extensions.KHR_materials_unlit;if(extension){material.unlit=true;}gltfScenegraph.removeObjectExtension(material,KHR_MATERIALS_UNLIT);}}catch(err){_iterator51.e(err);}finally{_iterator51.f();}case 5:case"end":return _context48.stop();}}},_callee44);}));return _decode$4.apply(this,arguments);}function encode$1(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var json=gltfScenegraph.json;if(gltfScenegraph.materials){var _iterator29=_createForOfIteratorHelper(json.materials||[]),_step29;try{for(_iterator29.s();!(_step29=_iterator29.n()).done;){var material=_step29.value;if(material.unlit){delete material.unlit;gltfScenegraph.addObjectExtension(material,KHR_MATERIALS_UNLIT,{});gltfScenegraph.addExtension(KHR_MATERIALS_UNLIT);}}}catch(err){_iterator29.e(err);}finally{_iterator29.f();}}}var KHR_materials_unlit=/*#__PURE__*/Object.freeze({__proto__:null,name:name$1,decode:decode$1,encode:encode$1});var KHR_TECHNIQUES_WEBGL='KHR_techniques_webgl';var name=KHR_TECHNIQUES_WEBGL;function decode(_x82){return _decode.apply(this,arguments);}function _decode(){_decode=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee45(gltfData){var gltfScenegraph,json,extension,techniques,_iterator52,_step52,material,materialExtension;return _regeneratorRuntime().wrap(function _callee45$(_context49){while(1){switch(_context49.prev=_context49.next){case 0:gltfScenegraph=new GLTFScenegraph(gltfData);json=gltfScenegraph.json;extension=gltfScenegraph.getExtension(KHR_TECHNIQUES_WEBGL);if(extension){techniques=resolveTechniques(extension,gltfScenegraph);_iterator52=_createForOfIteratorHelper(json.materials||[]);try{for(_iterator52.s();!(_step52=_iterator52.n()).done;){material=_step52.value;materialExtension=gltfScenegraph.getObjectExtension(material,KHR_TECHNIQUES_WEBGL);if(materialExtension){material.technique=Object.assign({},materialExtension,techniques[materialExtension.technique]);material.technique.values=resolveValues(material.technique,gltfScenegraph);}gltfScenegraph.removeObjectExtension(material,KHR_TECHNIQUES_WEBGL);}}catch(err){_iterator52.e(err);}finally{_iterator52.f();}gltfScenegraph.removeExtension(KHR_TECHNIQUES_WEBGL);}case 4:case"end":return _context49.stop();}}},_callee45);}));return _decode.apply(this,arguments);}function encode(_x83,_x84){return _encode.apply(this,arguments);}function _encode(){_encode=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee46(gltfData,options){return _regeneratorRuntime().wrap(function _callee46$(_context50){while(1){switch(_context50.prev=_context50.next){case 0:case"end":return _context50.stop();}}},_callee46);}));return _encode.apply(this,arguments);}function resolveTechniques(techniquesExtension,gltfScenegraph){var _techniquesExtension$=techniquesExtension.programs,programs=_techniquesExtension$===void 0?[]:_techniquesExtension$,_techniquesExtension$2=techniquesExtension.shaders,shaders=_techniquesExtension$2===void 0?[]:_techniquesExtension$2,_techniquesExtension$3=techniquesExtension.techniques,techniques=_techniquesExtension$3===void 0?[]:_techniquesExtension$3;var textDecoder=new TextDecoder();shaders.forEach(function(shader){if(Number.isFinite(shader.bufferView)){shader.code=textDecoder.decode(gltfScenegraph.getTypedArrayForBufferView(shader.bufferView));}else{throw new Error('KHR_techniques_webgl: no shader code');}});programs.forEach(function(program){program.fragmentShader=shaders[program.fragmentShader];program.vertexShader=shaders[program.vertexShader];});techniques.forEach(function(technique){technique.program=programs[technique.program];});return techniques;}function resolveValues(technique,gltfScenegraph){var values=Object.assign({},technique.values);Object.keys(technique.uniforms||{}).forEach(function(uniform){if(technique.uniforms[uniform].value&&!(uniform in values)){values[uniform]=technique.uniforms[uniform].value;}});Object.keys(values).forEach(function(uniform){if(_typeof(values[uniform])==='object'&&values[uniform].index!==undefined){values[uniform].texture=gltfScenegraph.getTexture(values[uniform].index);}});return values;}var KHR_techniques_webgl=/*#__PURE__*/Object.freeze({__proto__:null,name:name,decode:decode,encode:encode});var EXTENSIONS=[EXT_meshopt_compression,EXT_texture_webp,KHR_texture_basisu,KHR_draco_mesh_compression,KHR_lights_punctual,KHR_materials_unlit,KHR_techniques_webgl];function preprocessExtensions(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var context=arguments.length>2?arguments[2]:undefined;var extensions=EXTENSIONS.filter(function(extension){return useExtension(extension.name,options);});var _iterator30=_createForOfIteratorHelper(extensions),_step30;try{for(_iterator30.s();!(_step30=_iterator30.n()).done;){var extension=_step30.value;var _extension$preprocess;(_extension$preprocess=extension.preprocess)===null||_extension$preprocess===void 0?void 0:_extension$preprocess.call(extension,gltf,options,context);}}catch(err){_iterator30.e(err);}finally{_iterator30.f();}}function decodeExtensions(_x85){return _decodeExtensions.apply(this,arguments);}function _decodeExtensions(){_decodeExtensions=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee47(gltf){var options,context,extensions,_iterator53,_step53,extension,_extension$decode,_args45=arguments;return _regeneratorRuntime().wrap(function _callee47$(_context51){while(1){switch(_context51.prev=_context51.next){case 0:options=_args45.length>1&&_args45[1]!==undefined?_args45[1]:{};context=_args45.length>2?_args45[2]:undefined;extensions=EXTENSIONS.filter(function(extension){return useExtension(extension.name,options);});_iterator53=_createForOfIteratorHelper(extensions);_context51.prev=4;_iterator53.s();case 6:if((_step53=_iterator53.n()).done){_context51.next=12;break;}extension=_step53.value;_context51.next=10;return(_extension$decode=extension.decode)===null||_extension$decode===void 0?void 0:_extension$decode.call(extension,gltf,options,context);case 10:_context51.next=6;break;case 12:_context51.next=17;break;case 14:_context51.prev=14;_context51.t0=_context51["catch"](4);_iterator53.e(_context51.t0);case 17:_context51.prev=17;_iterator53.f();return _context51.finish(17);case 20:case"end":return _context51.stop();}}},_callee47,null,[[4,14,17,20]]);}));return _decodeExtensions.apply(this,arguments);}function useExtension(extensionName,options){var _options$gltf;var excludes=(options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.excludeExtensions)||{};var exclude=extensionName in excludes&&!excludes[extensionName];return!exclude;}var KHR_BINARY_GLTF='KHR_binary_glTF';function preprocess(gltfData){var gltfScenegraph=new GLTFScenegraph(gltfData);var json=gltfScenegraph.json;var _iterator31=_createForOfIteratorHelper(json.images||[]),_step31;try{for(_iterator31.s();!(_step31=_iterator31.n()).done;){var _image7=_step31.value;var extension=gltfScenegraph.getObjectExtension(_image7,KHR_BINARY_GLTF);if(extension){Object.assign(_image7,extension);}gltfScenegraph.removeObjectExtension(_image7,KHR_BINARY_GLTF);}}catch(err){_iterator31.e(err);}finally{_iterator31.f();}if(json.buffers&&json.buffers[0]){delete json.buffers[0].uri;}gltfScenegraph.removeExtension(KHR_BINARY_GLTF);}var GLTF_ARRAYS={accessors:'accessor',animations:'animation',buffers:'buffer',bufferViews:'bufferView',images:'image',materials:'material',meshes:'mesh',nodes:'node',samplers:'sampler',scenes:'scene',skins:'skin',textures:'texture'};var GLTF_KEYS={accessor:'accessors',animations:'animation',buffer:'buffers',bufferView:'bufferViews',image:'images',material:'materials',mesh:'meshes',node:'nodes',sampler:'samplers',scene:'scenes',skin:'skins',texture:'textures'};var GLTFV1Normalizer=/*#__PURE__*/function(){function GLTFV1Normalizer(){_classCallCheck(this,GLTFV1Normalizer);_defineProperty(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}});_defineProperty(this,"json",void 0);}_createClass(GLTFV1Normalizer,[{key:"normalize",value:function normalize(gltf,options){this.json=gltf.json;var json=gltf.json;switch(json.asset&&json.asset.version){case'2.0':return;case undefined:case'1.0':break;default:console.warn("glTF: Unknown version ".concat(json.asset.version));return;}if(!options.normalize){throw new Error('glTF v1 is not supported.');}console.warn('Converting glTF v1 to glTF v2 format. This is experimental and may fail.');this._addAsset(json);this._convertTopLevelObjectsToArrays(json);preprocess(gltf);this._convertObjectIdsToArrayIndices(json);this._updateObjects(json);this._updateMaterial(json);}},{key:"_addAsset",value:function _addAsset(json){json.asset=json.asset||{};json.asset.version='2.0';json.asset.generator=json.asset.generator||'Normalized to glTF 2.0 by loaders.gl';}},{key:"_convertTopLevelObjectsToArrays",value:function _convertTopLevelObjectsToArrays(json){for(var arrayName in GLTF_ARRAYS){this._convertTopLevelObjectToArray(json,arrayName);}}},{key:"_convertTopLevelObjectToArray",value:function _convertTopLevelObjectToArray(json,mapName){var objectMap=json[mapName];if(!objectMap||Array.isArray(objectMap)){return;}json[mapName]=[];for(var id in objectMap){var object=objectMap[id];object.id=object.id||id;var index=json[mapName].length;json[mapName].push(object);this.idToIndexMap[mapName][id]=index;}}},{key:"_convertObjectIdsToArrayIndices",value:function _convertObjectIdsToArrayIndices(json){for(var arrayName in GLTF_ARRAYS){this._convertIdsToIndices(json,arrayName);}if('scene'in json){json.scene=this._convertIdToIndex(json.scene,'scene');}var _iterator32=_createForOfIteratorHelper(json.textures),_step32;try{for(_iterator32.s();!(_step32=_iterator32.n()).done;){var texture=_step32.value;this._convertTextureIds(texture);}}catch(err){_iterator32.e(err);}finally{_iterator32.f();}var _iterator33=_createForOfIteratorHelper(json.meshes),_step33;try{for(_iterator33.s();!(_step33=_iterator33.n()).done;){var _mesh5=_step33.value;this._convertMeshIds(_mesh5);}}catch(err){_iterator33.e(err);}finally{_iterator33.f();}var _iterator34=_createForOfIteratorHelper(json.nodes),_step34;try{for(_iterator34.s();!(_step34=_iterator34.n()).done;){var _node4=_step34.value;this._convertNodeIds(_node4);}}catch(err){_iterator34.e(err);}finally{_iterator34.f();}var _iterator35=_createForOfIteratorHelper(json.scenes),_step35;try{for(_iterator35.s();!(_step35=_iterator35.n()).done;){var _node5=_step35.value;this._convertSceneIds(_node5);}}catch(err){_iterator35.e(err);}finally{_iterator35.f();}}},{key:"_convertTextureIds",value:function _convertTextureIds(texture){if(texture.source){texture.source=this._convertIdToIndex(texture.source,'image');}}},{key:"_convertMeshIds",value:function _convertMeshIds(mesh){var _iterator36=_createForOfIteratorHelper(mesh.primitives),_step36;try{for(_iterator36.s();!(_step36=_iterator36.n()).done;){var _primitive3=_step36.value;var attributes=_primitive3.attributes,indices=_primitive3.indices,material=_primitive3.material;for(var attributeName in attributes){attributes[attributeName]=this._convertIdToIndex(attributes[attributeName],'accessor');}if(indices){_primitive3.indices=this._convertIdToIndex(indices,'accessor');}if(material){_primitive3.material=this._convertIdToIndex(material,'material');}}}catch(err){_iterator36.e(err);}finally{_iterator36.f();}}},{key:"_convertNodeIds",value:function _convertNodeIds(node){var _this122=this;if(node.children){node.children=node.children.map(function(child){return _this122._convertIdToIndex(child,'node');});}if(node.meshes){node.meshes=node.meshes.map(function(mesh){return _this122._convertIdToIndex(mesh,'mesh');});}}},{key:"_convertSceneIds",value:function _convertSceneIds(scene){var _this123=this;if(scene.nodes){scene.nodes=scene.nodes.map(function(node){return _this123._convertIdToIndex(node,'node');});}}},{key:"_convertIdsToIndices",value:function _convertIdsToIndices(json,topLevelArrayName){if(!json[topLevelArrayName]){console.warn("gltf v1: json doesn't contain attribute ".concat(topLevelArrayName));json[topLevelArrayName]=[];}var _iterator37=_createForOfIteratorHelper(json[topLevelArrayName]),_step37;try{for(_iterator37.s();!(_step37=_iterator37.n()).done;){var object=_step37.value;for(var key in object){var id=object[key];var index=this._convertIdToIndex(id,key);object[key]=index;}}}catch(err){_iterator37.e(err);}finally{_iterator37.f();}}},{key:"_convertIdToIndex",value:function _convertIdToIndex(id,key){var arrayName=GLTF_KEYS[key];if(arrayName in this.idToIndexMap){var index=this.idToIndexMap[arrayName][id];if(!Number.isFinite(index)){throw new Error("gltf v1: failed to resolve ".concat(key," with id ").concat(id));}return index;}return id;}},{key:"_updateObjects",value:function _updateObjects(json){var _iterator38=_createForOfIteratorHelper(this.json.buffers),_step38;try{for(_iterator38.s();!(_step38=_iterator38.n()).done;){var buffer=_step38.value;delete buffer.type;}}catch(err){_iterator38.e(err);}finally{_iterator38.f();}}},{key:"_updateMaterial",value:function _updateMaterial(json){var _iterator39=_createForOfIteratorHelper(json.materials),_step39;try{var _loop6=function _loop6(){var material=_step39.value;material.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var textureId=((_material$values=material.values)===null||_material$values===void 0?void 0:_material$values.tex)||((_material$values2=material.values)===null||_material$values2===void 0?void 0:_material$values2.texture2d_0);var textureIndex=json.textures.findIndex(function(texture){return texture.id===textureId;});if(textureIndex!==-1){material.pbrMetallicRoughness.baseColorTexture={index:textureIndex};}};for(_iterator39.s();!(_step39=_iterator39.n()).done;){var _material$values,_material$values2;_loop6();}}catch(err){_iterator39.e(err);}finally{_iterator39.f();}}}]);return GLTFV1Normalizer;}();function normalizeGLTFV1(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};return new GLTFV1Normalizer().normalize(gltf,options);}var COMPONENTS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};var BYTES={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4};var GL_SAMPLER={TEXTURE_MAG_FILTER:0x2800,TEXTURE_MIN_FILTER:0x2801,TEXTURE_WRAP_S:0x2802,TEXTURE_WRAP_T:0x2803,REPEAT:0x2901,LINEAR:0x2601,NEAREST_MIPMAP_LINEAR:0x2702};var SAMPLER_PARAMETER_GLTF_TO_GL={magFilter:GL_SAMPLER.TEXTURE_MAG_FILTER,minFilter:GL_SAMPLER.TEXTURE_MIN_FILTER,wrapS:GL_SAMPLER.TEXTURE_WRAP_S,wrapT:GL_SAMPLER.TEXTURE_WRAP_T};var DEFAULT_SAMPLER=(_DEFAULT_SAMPLER={},_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_MAG_FILTER,GL_SAMPLER.LINEAR),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_MIN_FILTER,GL_SAMPLER.NEAREST_MIPMAP_LINEAR),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_WRAP_S,GL_SAMPLER.REPEAT),_defineProperty2(_DEFAULT_SAMPLER,GL_SAMPLER.TEXTURE_WRAP_T,GL_SAMPLER.REPEAT),_DEFAULT_SAMPLER);function getBytesFromComponentType(componentType){return BYTES[componentType];}function getSizeFromAccessorType(type){return COMPONENTS[type];}var GLTFPostProcessor=/*#__PURE__*/function(){function GLTFPostProcessor(){_classCallCheck(this,GLTFPostProcessor);_defineProperty(this,"baseUri",'');_defineProperty(this,"json",{});_defineProperty(this,"buffers",[]);_defineProperty(this,"images",[]);}_createClass(GLTFPostProcessor,[{key:"postProcess",value:function postProcess(gltf){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var json=gltf.json,_gltf$buffers=gltf.buffers,buffers=_gltf$buffers===void 0?[]:_gltf$buffers,_gltf$images=gltf.images,images=_gltf$images===void 0?[]:_gltf$images,_gltf$baseUri=gltf.baseUri,baseUri=_gltf$baseUri===void 0?'':_gltf$baseUri;assert$1(json);this.baseUri=baseUri;this.json=json;this.buffers=buffers;this.images=images;this._resolveTree(this.json,options);return this.json;}},{key:"_resolveTree",value:function _resolveTree(json){var _this124=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(json.bufferViews){json.bufferViews=json.bufferViews.map(function(bufView,i){return _this124._resolveBufferView(bufView,i);});}if(json.images){json.images=json.images.map(function(image,i){return _this124._resolveImage(image,i);});}if(json.samplers){json.samplers=json.samplers.map(function(sampler,i){return _this124._resolveSampler(sampler,i);});}if(json.textures){json.textures=json.textures.map(function(texture,i){return _this124._resolveTexture(texture,i);});}if(json.accessors){json.accessors=json.accessors.map(function(accessor,i){return _this124._resolveAccessor(accessor,i);});}if(json.materials){json.materials=json.materials.map(function(material,i){return _this124._resolveMaterial(material,i);});}if(json.meshes){json.meshes=json.meshes.map(function(mesh,i){return _this124._resolveMesh(mesh,i);});}if(json.nodes){json.nodes=json.nodes.map(function(node,i){return _this124._resolveNode(node,i);});}if(json.skins){json.skins=json.skins.map(function(skin,i){return _this124._resolveSkin(skin,i);});}if(json.scenes){json.scenes=json.scenes.map(function(scene,i){return _this124._resolveScene(scene,i);});}if(json.scene!==undefined){json.scene=json.scenes[this.json.scene];}}},{key:"getScene",value:function getScene(index){return this._get('scenes',index);}},{key:"getNode",value:function getNode(index){return this._get('nodes',index);}},{key:"getSkin",value:function getSkin(index){return this._get('skins',index);}},{key:"getMesh",value:function getMesh(index){return this._get('meshes',index);}},{key:"getMaterial",value:function getMaterial(index){return this._get('materials',index);}},{key:"getAccessor",value:function getAccessor(index){return this._get('accessors',index);}},{key:"getCamera",value:function getCamera(index){return null;}},{key:"getTexture",value:function getTexture(index){return this._get('textures',index);}},{key:"getSampler",value:function getSampler(index){return this._get('samplers',index);}},{key:"getImage",value:function getImage(index){return this._get('images',index);}},{key:"getBufferView",value:function getBufferView(index){return this._get('bufferViews',index);}},{key:"getBuffer",value:function getBuffer(index){return this._get('buffers',index);}},{key:"_get",value:function _get(array,index){if(_typeof(index)==='object'){return index;}var object=this.json[array]&&this.json[array][index];if(!object){console.warn("glTF file error: Could not find ".concat(array,"[").concat(index,"]"));}return object;}},{key:"_resolveScene",value:function _resolveScene(scene,index){var _this125=this;scene.id=scene.id||"scene-".concat(index);scene.nodes=(scene.nodes||[]).map(function(node){return _this125.getNode(node);});return scene;}},{key:"_resolveNode",value:function _resolveNode(node,index){var _this126=this;node.id=node.id||"node-".concat(index);if(node.children){node.children=node.children.map(function(child){return _this126.getNode(child);});}if(node.mesh!==undefined){node.mesh=this.getMesh(node.mesh);}else if(node.meshes!==undefined&&node.meshes.length){node.mesh=node.meshes.reduce(function(accum,meshIndex){var mesh=_this126.getMesh(meshIndex);accum.id=mesh.id;accum.primitives=accum.primitives.concat(mesh.primitives);return accum;},{primitives:[]});}if(node.camera!==undefined){node.camera=this.getCamera(node.camera);}if(node.skin!==undefined){node.skin=this.getSkin(node.skin);}return node;}},{key:"_resolveSkin",value:function _resolveSkin(skin,index){skin.id=skin.id||"skin-".concat(index);skin.inverseBindMatrices=this.getAccessor(skin.inverseBindMatrices);return skin;}},{key:"_resolveMesh",value:function _resolveMesh(mesh,index){var _this127=this;mesh.id=mesh.id||"mesh-".concat(index);if(mesh.primitives){mesh.primitives=mesh.primitives.map(function(primitive){primitive=_objectSpread({},primitive);var attributes=primitive.attributes;primitive.attributes={};for(var attribute in attributes){primitive.attributes[attribute]=_this127.getAccessor(attributes[attribute]);}if(primitive.indices!==undefined){primitive.indices=_this127.getAccessor(primitive.indices);}if(primitive.material!==undefined){primitive.material=_this127.getMaterial(primitive.material);}return primitive;});}return mesh;}},{key:"_resolveMaterial",value:function _resolveMaterial(material,index){material.id=material.id||"material-".concat(index);if(material.normalTexture){material.normalTexture=_objectSpread({},material.normalTexture);material.normalTexture.texture=this.getTexture(material.normalTexture.index);}if(material.occlusionTexture){material.occlustionTexture=_objectSpread({},material.occlustionTexture);material.occlusionTexture.texture=this.getTexture(material.occlusionTexture.index);}if(material.emissiveTexture){material.emmisiveTexture=_objectSpread({},material.emmisiveTexture);material.emissiveTexture.texture=this.getTexture(material.emissiveTexture.index);}if(!material.emissiveFactor){material.emissiveFactor=material.emmisiveTexture?[1,1,1]:[0,0,0];}if(material.pbrMetallicRoughness){material.pbrMetallicRoughness=_objectSpread({},material.pbrMetallicRoughness);var mr=material.pbrMetallicRoughness;if(mr.baseColorTexture){mr.baseColorTexture=_objectSpread({},mr.baseColorTexture);mr.baseColorTexture.texture=this.getTexture(mr.baseColorTexture.index);}if(mr.metallicRoughnessTexture){mr.metallicRoughnessTexture=_objectSpread({},mr.metallicRoughnessTexture);mr.metallicRoughnessTexture.texture=this.getTexture(mr.metallicRoughnessTexture.index);}}return material;}},{key:"_resolveAccessor",value:function _resolveAccessor(accessor,index){accessor.id=accessor.id||"accessor-".concat(index);if(accessor.bufferView!==undefined){accessor.bufferView=this.getBufferView(accessor.bufferView);}accessor.bytesPerComponent=getBytesFromComponentType(accessor.componentType);accessor.components=getSizeFromAccessorType(accessor.type);accessor.bytesPerElement=accessor.bytesPerComponent*accessor.components;if(accessor.bufferView){var buffer=accessor.bufferView.buffer;var _getAccessorArrayType2=getAccessorArrayTypeAndLength(accessor,accessor.bufferView),ArrayType=_getAccessorArrayType2.ArrayType,byteLength=_getAccessorArrayType2.byteLength;var byteOffset=(accessor.bufferView.byteOffset||0)+(accessor.byteOffset||0)+buffer.byteOffset;var cutBuffer=buffer.arrayBuffer.slice(byteOffset,byteOffset+byteLength);if(accessor.bufferView.byteStride){cutBuffer=this._getValueFromInterleavedBuffer(buffer,byteOffset,accessor.bufferView.byteStride,accessor.bytesPerElement,accessor.count);}accessor.value=new ArrayType(cutBuffer);}return accessor;}},{key:"_getValueFromInterleavedBuffer",value:function _getValueFromInterleavedBuffer(buffer,byteOffset,byteStride,bytesPerElement,count){var result=new Uint8Array(count*bytesPerElement);for(var _i510=0;_i5101&&arguments[1]!==undefined?arguments[1]:0;return"".concat(String.fromCharCode(dataView.getUint8(byteOffset+0))).concat(String.fromCharCode(dataView.getUint8(byteOffset+1))).concat(String.fromCharCode(dataView.getUint8(byteOffset+2))).concat(String.fromCharCode(dataView.getUint8(byteOffset+3)));}function isGLB(arrayBuffer){var byteOffset=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var dataView=new DataView(arrayBuffer);var _options$magic=options.magic,magic=_options$magic===void 0?MAGIC_glTF:_options$magic;var magic1=dataView.getUint32(byteOffset,false);return magic1===magic||magic1===MAGIC_glTF;}function parseGLBSync(glb,arrayBuffer){var byteOffset=arguments.length>2&&arguments[2]!==undefined?arguments[2]:0;var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var dataView=new DataView(arrayBuffer);var type=getMagicString(dataView,byteOffset+0);var version=dataView.getUint32(byteOffset+4,LE);var byteLength=dataView.getUint32(byteOffset+8,LE);Object.assign(glb,{header:{byteOffset:byteOffset,byteLength:byteLength,hasBinChunk:false},type:type,version:version,json:{},binChunks:[]});byteOffset+=GLB_FILE_HEADER_SIZE;switch(glb.version){case 1:return parseGLBV1(glb,dataView,byteOffset);case 2:return parseGLBV2(glb,dataView,byteOffset,options={});default:throw new Error("Invalid GLB version ".concat(glb.version,". Only supports v1 and v2."));}}function parseGLBV1(glb,dataView,byteOffset){assert$5(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);var contentLength=dataView.getUint32(byteOffset+0,LE);var contentFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;assert$5(contentFormat===GLB_V1_CONTENT_FORMAT_JSON);parseJSONChunk(glb,dataView,byteOffset,contentLength);byteOffset+=contentLength;byteOffset+=parseBINChunk(glb,dataView,byteOffset,glb.header.byteLength);return byteOffset;}function parseGLBV2(glb,dataView,byteOffset,options){assert$5(glb.header.byteLength>GLB_FILE_HEADER_SIZE+GLB_CHUNK_HEADER_SIZE);parseGLBChunksSync(glb,dataView,byteOffset,options);return byteOffset+glb.header.byteLength;}function parseGLBChunksSync(glb,dataView,byteOffset,options){while(byteOffset+8<=glb.header.byteLength){var chunkLength=dataView.getUint32(byteOffset+0,LE);var chunkFormat=dataView.getUint32(byteOffset+4,LE);byteOffset+=GLB_CHUNK_HEADER_SIZE;switch(chunkFormat){case GLB_CHUNK_TYPE_JSON:parseJSONChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_BIN:parseBINChunk(glb,dataView,byteOffset,chunkLength);break;case GLB_CHUNK_TYPE_JSON_XVIZ_DEPRECATED:if(!options.strict){parseJSONChunk(glb,dataView,byteOffset,chunkLength);}break;case GLB_CHUNK_TYPE_BIX_XVIZ_DEPRECATED:if(!options.strict){parseBINChunk(glb,dataView,byteOffset,chunkLength);}break;}byteOffset+=padToNBytes(chunkLength,4);}return byteOffset;}function parseJSONChunk(glb,dataView,byteOffset,chunkLength){var jsonChunk=new Uint8Array(dataView.buffer,byteOffset,chunkLength);var textDecoder=new TextDecoder('utf8');var jsonText=textDecoder.decode(jsonChunk);glb.json=JSON.parse(jsonText);return padToNBytes(chunkLength,4);}function parseBINChunk(glb,dataView,byteOffset,chunkLength){glb.header.hasBinChunk=true;glb.binChunks.push({byteOffset:byteOffset,byteLength:chunkLength,arrayBuffer:dataView.buffer});return padToNBytes(chunkLength,4);}function parseGLTF$1(_x86,_x87){return _parseGLTF$.apply(this,arguments);}function _parseGLTF$(){_parseGLTF$=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee48(gltf,arrayBufferOrString){var byteOffset,options,context,_options$gltf,_options$gltf2,_options$gltf3,_options$gltf4,promises,_promise,promise,_args46=arguments;return _regeneratorRuntime().wrap(function _callee48$(_context52){while(1){switch(_context52.prev=_context52.next){case 0:byteOffset=_args46.length>2&&_args46[2]!==undefined?_args46[2]:0;options=_args46.length>3?_args46[3]:undefined;context=_args46.length>4?_args46[4]:undefined;parseGLTFContainerSync(gltf,arrayBufferOrString,byteOffset,options);normalizeGLTFV1(gltf,{normalize:options===null||options===void 0?void 0:(_options$gltf=options.gltf)===null||_options$gltf===void 0?void 0:_options$gltf.normalize});preprocessExtensions(gltf,options,context);promises=[];if(!(options!==null&&options!==void 0&&(_options$gltf2=options.gltf)!==null&&_options$gltf2!==void 0&&_options$gltf2.loadBuffers&&gltf.json.buffers)){_context52.next=10;break;}_context52.next=10;return loadBuffers(gltf,options,context);case 10:if(options!==null&&options!==void 0&&(_options$gltf3=options.gltf)!==null&&_options$gltf3!==void 0&&_options$gltf3.loadImages){_promise=loadImages(gltf,options,context);promises.push(_promise);}promise=decodeExtensions(gltf,options,context);promises.push(promise);_context52.next=15;return Promise.all(promises);case 15:return _context52.abrupt("return",options!==null&&options!==void 0&&(_options$gltf4=options.gltf)!==null&&_options$gltf4!==void 0&&_options$gltf4.postProcess?postProcessGLTF(gltf,options):gltf);case 16:case"end":return _context52.stop();}}},_callee48);}));return _parseGLTF$.apply(this,arguments);}function parseGLTFContainerSync(gltf,data,byteOffset,options){if(options.uri){gltf.baseUri=options.uri;}if(data instanceof ArrayBuffer&&!isGLB(data,byteOffset,options)){var textDecoder=new TextDecoder();data=textDecoder.decode(data);}if(typeof data==='string'){gltf.json=parseJSON(data);}else if(data instanceof ArrayBuffer){var glb={};byteOffset=parseGLBSync(glb,data,byteOffset,options.glb);assert$1(glb.type==='glTF',"Invalid GLB magic string ".concat(glb.type));gltf._glb=glb;gltf.json=glb.json;}else{assert$1(false,'GLTF: must be ArrayBuffer or string');}var buffers=gltf.json.buffers||[];gltf.buffers=new Array(buffers.length).fill(null);if(gltf._glb&&gltf._glb.header.hasBinChunk){var binChunks=gltf._glb.binChunks;gltf.buffers[0]={arrayBuffer:binChunks[0].arrayBuffer,byteOffset:binChunks[0].byteOffset,byteLength:binChunks[0].byteLength};}var images=gltf.json.images||[];gltf.images=new Array(images.length).fill({});}function loadBuffers(_x88,_x89,_x90){return _loadBuffers.apply(this,arguments);}function _loadBuffers(){_loadBuffers=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee49(gltf,options,context){var buffers,_i604,buffer,_context$fetch,_response$arrayBuffer,_fetch,uri,response,arrayBuffer;return _regeneratorRuntime().wrap(function _callee49$(_context53){while(1){switch(_context53.prev=_context53.next){case 0:buffers=gltf.json.buffers||[];_i604=0;case 2:if(!(_i6041&&_args50[1]!==undefined?_args50[1]:{};context=_args50.length>2?_args50[2]:undefined;options=_objectSpread(_objectSpread({},GLTFLoader.options),options);options.gltf=_objectSpread(_objectSpread({},GLTFLoader.options.gltf),options.gltf);_options2=options,_options2$byteOffset=_options2.byteOffset,byteOffset=_options2$byteOffset===void 0?0:_options2$byteOffset;gltf={};_context56.next=8;return parseGLTF$1(gltf,arrayBuffer,byteOffset,options,context);case 8:return _context56.abrupt("return",_context56.sent);case 9:case"end":return _context56.stop();}}},_callee52);}));return _parse$3.apply(this,arguments);}var GLTFSceneModelLoader=/*#__PURE__*/function(){function GLTFSceneModelLoader(cfg){_classCallCheck(this,GLTFSceneModelLoader);}_createClass(GLTFSceneModelLoader,[{key:"load",value:function load(plugin,src,metaModelJSON,options,sceneModel,ok,error){options=options||{};loadGLTF(plugin,src,metaModelJSON,options,sceneModel,function(){core.scheduleTask(function(){sceneModel.scene.fire("modelLoaded",sceneModel.id);// FIXME: Assumes listeners know order of these two events sceneModel.fire("loaded",true,false);});if(ok){ok();}},function(msg){plugin.error(msg);if(error){error(msg);}sceneModel.fire("error",msg);});}},{key:"parse",value:function parse(plugin,gltf,metaModelJSON,options,sceneModel,ok,error){options=options||{};parseGLTF(plugin,"",gltf,metaModelJSON,options,sceneModel,function(){sceneModel.scene.fire("modelLoaded",sceneModel.id);// FIXME: Assumes listeners know order of these two events -sceneModel.fire("loaded",true,false);if(ok){ok();}});}}]);return GLTFSceneModelLoader;}();function getMetaModelCorrections(metaModelJSON){var eachRootStats={};var eachChildRoot={};var metaObjects=metaModelJSON.metaObjects||[];var metaObjectsMap={};for(var _i509=0,len=metaObjects.length;_i5090){for(var _i516=0;_i5160){for(var _i518=0;_i5180){if(nodeName===undefined||nodeName===null){ctx.log("Warning: 'name' properties not found on glTF scene nodes - will randomly-generate object IDs in XKT");}var entityId=nodeName;// Fall back on generated ID when `name` not found on glTF scene node(s) // if (!!entityId && sceneModel.entities[entityId]) { // ctx.log(`Warning: Two or more glTF nodes found with same 'name' attribute: '${nodeName} - will randomly-generating an object ID in XKT`); @@ -25041,7 +25047,7 @@ sceneModel.createEntity({id:entityId,meshIds:deferredMeshIds,isObject:true});def * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models} */,set:function set(value){this._objectDefaults=value||IFCObjectDefaults;}},{key:"load",value:function load(){var _this129=this;var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true,dtxEnabled:params.dtxEnabled}));var modelId=sceneModel.id;// In case ID was auto-generated if(!params.src&&!params.gltf){this.error("load() param expected: src or gltf");return sceneModel;// Return new empty model -}if(params.metaModelSrc||params.metaModelJSON){var objectDefaults=params.objectDefaults||this._objectDefaults||IFCObjectDefaults;var processMetaModelJSON=function processMetaModelJSON(metaModelJSON){_this129.viewer.metaScene.createMetaModel(modelId,metaModelJSON,{includeTypes:params.includeTypes,excludeTypes:params.excludeTypes});_this129.viewer.scene.canvas.spinner.processes--;var includeTypes;if(params.includeTypes){includeTypes={};for(var _i518=0,len=params.includeTypes.length;_i518=boundary[0]*scale&&s<=(boundary[0]+boundary[2])*scale&&t>=boundary[1]*scale&&t<=(boundary[1]+boundary[3])*scale){return i;}}}return-1;};this.setAreaHighlighted=function(areaId,highlighted){var area=areas[areaId];if(!area){throw"Area not found: "+areaId;}area.highlighted=!!highlighted;paint();};this.getAreaDir=function(areaId){var area=areas[areaId];if(!area){throw"Unknown area: "+areaId;}return area.dir;};this.getAreaUp=function(areaId){var area=areas[areaId];if(!area){throw"Unknown area: "+areaId;}return area.up;};this.getImage=function(){return this._textureCanvas;};this.destroy=function(){if(this._textureCanvas){this._textureCanvas.parentNode.removeChild(this._textureCanvas);this._textureCanvas=null;}};}var tempVec3a$4=math.vec3();var tempVec3b$1=math.vec3();math.mat4();/** * {@link Viewer} plugin that lets us look at the entire {@link Scene} from along a chosen axis or diagonal. * @@ -26078,7 +26084,7 @@ for(var _id4 in this._controls){if(this._controls.hasOwnProperty(_id4)){this._co * These are created and destroyed automatically as models are loaded and destroyed. * * @type {{String: {String:Storey}}} - */_this139.modelStoreys={};_this139._fitStoreyMaps=!!cfg.fitStoreyMaps;_this139._onModelLoaded=_this139.viewer.scene.on("modelLoaded",function(modelId){_this139._registerModelStoreys(modelId);_this139.fire("storeys",_this139.storeys);});return _this139;}_createClass(StoreyViewsPlugin,[{key:"_registerModelStoreys",value:function _registerModelStoreys(modelId){var _this140=this;var viewer=this.viewer;var scene=viewer.scene;var metaScene=viewer.metaScene;var metaModel=metaScene.metaModels[modelId];var model=scene.models[modelId];if(!metaModel||!metaModel.rootMetaObjects){return;}var rootMetaObjects=metaModel.rootMetaObjects;for(var j=0,lenj=rootMetaObjects.length;j0.5?childObjectIds.length:0;var storey=new Storey(this,model.aabb,storeyAABB,modelId,storeyId,numObjects);storey._onModelDestroyed=model.once("destroyed",function(){_this140._deregisterModelStoreys(modelId);_this140.fire("storeys",_this140.storeys);});this.storeys[storeyId]=storey;if(!this.modelStoreys[modelId]){this.modelStoreys[modelId]={};}this.modelStoreys[modelId][storeyId]=storey;}}}},{key:"_deregisterModelStoreys",value:function _deregisterModelStoreys(modelId){var storeys=this.modelStoreys[modelId];if(storeys){var scene=this.viewer.scene;for(var storyObjectId in storeys){if(storeys.hasOwnProperty(storyObjectId)){var storey=storeys[storyObjectId];var model=scene.models[storey.modelId];if(model){model.off(storey._onModelDestroyed);}delete this.storeys[storyObjectId];}}delete this.modelStoreys[modelId];}}/** + */_this139.modelStoreys={};_this139._fitStoreyMaps=!!cfg.fitStoreyMaps;_this139._onModelLoaded=_this139.viewer.scene.on("modelLoaded",function(modelId){_this139._registerModelStoreys(modelId);_this139.fire("storeys",_this139.storeys);});return _this139;}_createClass(StoreyViewsPlugin,[{key:"_registerModelStoreys",value:function _registerModelStoreys(modelId){var _this140=this;var viewer=this.viewer;var scene=viewer.scene;var metaScene=viewer.metaScene;var metaModel=metaScene.metaModels[modelId];var model=scene.models[modelId];if(!metaModel||!metaModel.rootMetaObjects){return;}var rootMetaObjects=metaModel.rootMetaObjects;for(var j=0,lenj=rootMetaObjects.length;j0.5?childObjectIds.length:0;var storey=new Storey(this,model.aabb,storeyAABB,modelId,storeyId,numObjects);storey._onModelDestroyed=model.once("destroyed",function(){_this140._deregisterModelStoreys(modelId);_this140.fire("storeys",_this140.storeys);});this.storeys[storeyId]=storey;if(!this.modelStoreys[modelId]){this.modelStoreys[modelId]={};}this.modelStoreys[modelId][storeyId]=storey;}}}},{key:"_deregisterModelStoreys",value:function _deregisterModelStoreys(modelId){var storeys=this.modelStoreys[modelId];if(storeys){var scene=this.viewer.scene;for(var storyObjectId in storeys){if(storeys.hasOwnProperty(storyObjectId)){var storey=storeys[storyObjectId];var model=scene.models[storey.modelId];if(model){model.off(storey._onModelDestroyed);}delete this.storeys[storyObjectId];}}delete this.modelStoreys[modelId];}}/** * When true, the elements of each floor map image will be proportionally resized to encompass the entire image. This leads to varying scales among different * floor map images. If false, each floor map image will display the model's extents, ensuring a consistent scale across all images. * @returns {*|boolean} @@ -26448,7 +26454,7 @@ var sectionPlane=new SectionPlane(this.viewer.scene,{id:params.id,pos:params.pos * @param {String} id ID of the {@link SectionPlane}. */},{key:"destroySectionPlane",value:function destroySectionPlane(id){var sectionPlane=this.viewer.scene.sectionPlanes[id];if(!sectionPlane){this.error("SectionPlane not found: "+id);return;}this._sectionPlaneDestroyed(sectionPlane);sectionPlane.destroy();if(id===this._shownControlId){this._shownControlId=null;}}},{key:"_sectionPlaneDestroyed",value:function _sectionPlaneDestroyed(sectionPlane){if(this._overview){this._overview.removeSectionPlane(sectionPlane);}var control=this._controls[sectionPlane.id];if(!control){return;}control.setVisible(false);control._setSectionPlane(null);delete this._controls[sectionPlane.id];this._freeControls.push(control);}/** * Destroys all {@link SectionPlane}s created by this FaceAlignedSectionPlanesPlugin. - */},{key:"clear",value:function clear(){var ids=Object.keys(this._sectionPlanes);for(var _i525=0,len=ids.length;_i525>5&0x1F)/31;b=(packedColor>>10&0x1F)/31;}else{r=defaultR;g=defaultG;b=defaultB;}if(splitMeshes&&r!==lastR||g!==lastG||b!==lastB){if(lastR!==null){newMesh=true;}lastR=r;lastG=g;lastB=b;}}for(var _i526=1;_i526<=3;_i526++){var vertexstart=start+_i526*12;positions.push(reader.getFloat32(vertexstart,true));positions.push(reader.getFloat32(vertexstart+4,true));positions.push(reader.getFloat32(vertexstart+8,true));normals.push(normalX,normalY,normalZ);if(hasColors){colors.push(r,g,b,1);// TODO: handle alpha +var dataOffset=84;var faceLength=12*4+2;var positions=[];var normals=[];var splitMeshes=options.splitMeshes;for(var face=0;face>5&0x1F)/31;b=(packedColor>>10&0x1F)/31;}else{r=defaultR;g=defaultG;b=defaultB;}if(splitMeshes&&r!==lastR||g!==lastG||b!==lastB){if(lastR!==null){newMesh=true;}lastR=r;lastG=g;lastB=b;}}for(var _i528=1;_i528<=3;_i528++){var vertexstart=start+_i528*12;positions.push(reader.getFloat32(vertexstart,true));positions.push(reader.getFloat32(vertexstart+4,true));positions.push(reader.getFloat32(vertexstart+8,true));normals.push(normalX,normalY,normalZ);if(hasColors){colors.push(r,g,b,1);// TODO: handle alpha }}if(splitMeshes&&newMesh){addMesh(modelNode,positions,normals,colors,material,options);positions=[];normals=[];colors=colors?[]:null;newMesh=false;}}if(positions.length>0){addMesh(modelNode,positions,normals,colors,material,options);}}function parseASCII(plugin,data,modelNode,options){var faceRegex=/facet([\s\S]*?)endfacet/g;var faceCounter=0;var floatRegex=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source;var vertexRegex=new RegExp('vertex'+floatRegex+floatRegex+floatRegex,'g');var normalRegex=new RegExp('normal'+floatRegex+floatRegex+floatRegex,'g');var positions=[];var normals=[];var colors=null;var normalx;var normaly;var normalz;var result;var verticesPerFace;var normalsPerFace;var text;while((result=faceRegex.exec(data))!==null){verticesPerFace=0;normalsPerFace=0;text=result[0];while((result=normalRegex.exec(text))!==null){normalx=parseFloat(result[1]);normaly=parseFloat(result[2]);normalz=parseFloat(result[3]);normalsPerFace++;}while((result=vertexRegex.exec(text))!==null){positions.push(parseFloat(result[1]),parseFloat(result[2]),parseFloat(result[3]));normals.push(normalx,normaly,normalz);verticesPerFace++;}if(normalsPerFace!==1){plugin.error("Error in normal of face "+faceCounter);}if(verticesPerFace!==3){plugin.error("Error in positions of face "+faceCounter);}faceCounter++;}var material=new MetallicMaterial(modelNode,{roughness:0.5});// var material = new PhongMaterial(modelNode, { // diffuse: [0.4, 0.4, 0.4], // reflectivity: 1, // specular: [0.5, 0.5, 1.0] // }); -addMesh(modelNode,positions,normals,colors,material,options);}function addMesh(modelNode,positions,normals,colors,material,options){var indices=new Int32Array(positions.length/3);for(var ni=0,len=indices.length;ni0?normals:null;colors=colors&&colors.length>0?colors:null;if(options.smoothNormals){math.faceToVertexNormals(positions,normals,options);}var origin=tempVec3a$1;worldToRTCPositions(positions,positions,origin);var geometry=new ReadableGeometry(modelNode,{primitive:"triangles",positions:positions,normals:normals,colors:colors,indices:indices});var mesh=new Mesh(modelNode,{origin:origin[0]!==0||origin[1]!==0||origin[2]!==0?origin:null,geometry:geometry,material:material,edges:options.edges});modelNode.addChild(mesh);}function ensureString(buffer){if(typeof buffer!=='string'){return decodeText(new Uint8Array(buffer));}return buffer;}function ensureBinary(buffer){if(typeof buffer==='string'){var arrayBuffer=new Uint8Array(buffer.length);for(var _i527=0;_i5270?normals:null;colors=colors&&colors.length>0?colors:null;if(options.smoothNormals){math.faceToVertexNormals(positions,normals,options);}var origin=tempVec3a$1;worldToRTCPositions(positions,positions,origin);var geometry=new ReadableGeometry(modelNode,{primitive:"triangles",positions:positions,normals:normals,colors:colors,indices:indices});var mesh=new Mesh(modelNode,{origin:origin[0]!==0||origin[1]!==0||origin[2]!==0?origin:null,geometry:geometry,material:material,edges:options.edges});modelNode.addChild(mesh);}function ensureString(buffer){if(typeof buffer!=='string'){return decodeText(new Uint8Array(buffer));}return buffer;}function ensureBinary(buffer){if(typeof buffer==='string'){var arrayBuffer=new Uint8Array(buffer.length);for(var _i529=0;_i529STL files. * @@ -27141,12 +27147,12 @@ addMesh(modelNode,positions,normals,colors,material,options);}function addMesh(m */_this149.errors=[];/** * True if errors were found generating this TreeView. * @type {boolean} - */_this149.valid=true;var containerElement=cfg.containerElement||document.getElementById(cfg.containerElementId);if(!(containerElement instanceof HTMLElement)){_this149.error("Mandatory config expected: valid containerElementId or containerElement");return _possibleConstructorReturn(_this149);}for(var _i529=0;;_i529++){if(!treeViews[_i529]){treeViews[_i529]=_assertThisInitialized(_this149);_this149._index=_i529;_this149._id="tree-".concat(_i529);break;}}_this149._containerElement=containerElement;_this149._metaModels={};_this149._autoAddModels=cfg.autoAddModels!==false;_this149._autoExpandDepth=cfg.autoExpandDepth||0;_this149._sortNodes=cfg.sortNodes!==false;_this149._viewer=viewer;_this149._rootElement=null;_this149._muteSceneEvents=false;_this149._muteTreeEvents=false;_this149._rootNodes=[];_this149._objectNodes={};// Object ID -> Node + */_this149.valid=true;var containerElement=cfg.containerElement||document.getElementById(cfg.containerElementId);if(!(containerElement instanceof HTMLElement)){_this149.error("Mandatory config expected: valid containerElementId or containerElement");return _possibleConstructorReturn(_this149);}for(var _i531=0;;_i531++){if(!treeViews[_i531]){treeViews[_i531]=_assertThisInitialized(_this149);_this149._index=_i531;_this149._id="tree-".concat(_i531);break;}}_this149._containerElement=containerElement;_this149._metaModels={};_this149._autoAddModels=cfg.autoAddModels!==false;_this149._autoExpandDepth=cfg.autoExpandDepth||0;_this149._sortNodes=cfg.sortNodes!==false;_this149._viewer=viewer;_this149._rootElement=null;_this149._muteSceneEvents=false;_this149._muteTreeEvents=false;_this149._rootNodes=[];_this149._objectNodes={};// Object ID -> Node _this149._nodeNodes={};// Node ID -> Node _this149._rootNames={};// Node ID -> Root name _this149._sortNodes=cfg.sortNodes;_this149._pruneEmptyNodes=cfg.pruneEmptyNodes;_this149._showListItemElementId=null;_this149._renderService=cfg.renderService||new RenderService();if(!_this149._renderService){throw new Error('TreeViewPlugin: no render service set');}_this149._containerElement.oncontextmenu=function(e){e.preventDefault();};_this149._onObjectVisibility=_this149._viewer.scene.on("objectVisibility",function(entity){if(_this149._muteSceneEvents){return;}var objectId=entity.id;var node=_this149._objectNodes[objectId];if(!node){return;// Not in this tree }var visible=entity.visible;var updated=visible!==node.checked;if(!updated){return;}_this149._muteTreeEvents=true;node.checked=visible;if(visible){node.numVisibleEntities++;}else{node.numVisibleEntities--;}_this149._renderService.setCheckbox(node.nodeId,visible);var parent=node.parent;while(parent){parent.checked=visible;if(visible){parent.numVisibleEntities++;}else{parent.numVisibleEntities--;}_this149._renderService.setCheckbox(parent.nodeId,parent.numVisibleEntities>0);parent=parent.parent;}_this149._muteTreeEvents=false;});_this149._onObjectXrayed=_this149._viewer.scene.on('objectXRayed',function(entity){if(_this149._muteSceneEvents){return;}var objectId=entity.id;var node=_this149._objectNodes[objectId];if(!node){return;// Not in this tree -}_this149._muteTreeEvents=true;var xrayed=entity.xrayed;var updated=xrayed!==node.xrayed;if(!updated){return;}node.xrayed=xrayed;_this149._renderService.setXRayed(node.nodeId,xrayed);_this149._muteTreeEvents=false;});_this149._switchExpandHandler=function(event){event.preventDefault();event.stopPropagation();var switchElement=event.target;_this149._expandSwitchElement(switchElement);};_this149._switchCollapseHandler=function(event){event.preventDefault();event.stopPropagation();var switchElement=event.target;_this149._collapseSwitchElement(switchElement);};_this149._checkboxChangeHandler=function(event){if(_this149._muteTreeEvents){return;}_this149._muteSceneEvents=true;var checkbox=event.target;var visible=_this149._renderService.isChecked(checkbox);var nodeId=_this149._renderService.getIdFromCheckbox(checkbox);var checkedNode=_this149._nodeNodes[nodeId];var objects=_this149._viewer.scene.objects;var numUpdated=0;_this149._withNodeTree(checkedNode,function(node){var objectId=node.objectId;var entity=objects[objectId];var isLeaf=node.children.length===0;node.numVisibleEntities=visible?node.numEntities:0;if(isLeaf&&visible!==node.checked){numUpdated++;}node.checked=visible;_this149._renderService.setCheckbox(node.nodeId,visible);if(entity){entity.visible=visible;}});var parent=checkedNode.parent;while(parent){parent.checked=visible;if(visible){parent.numVisibleEntities+=numUpdated;}else{parent.numVisibleEntities-=numUpdated;}_this149._renderService.setCheckbox(parent.nodeId,parent.numVisibleEntities>0);parent=parent.parent;}_this149._muteSceneEvents=false;};_this149._hierarchy=cfg.hierarchy||"containment";_this149._autoExpandDepth=cfg.autoExpandDepth||0;if(_this149._autoAddModels){var modelIds=Object.keys(_this149.viewer.metaScene.metaModels);for(var _i530=0,len=modelIds.length;_i5300);parent=parent.parent;}_this149._muteSceneEvents=false;};_this149._hierarchy=cfg.hierarchy||"containment";_this149._autoExpandDepth=cfg.autoExpandDepth||0;if(_this149._autoAddModels){var modelIds=Object.keys(_this149.viewer.metaScene.metaModels);for(var _i532=0,len=modelIds.length;_i5320;break;case"containment":default:this.valid=this._rootNodes.length>0;break;}return this.valid;}},{key:"_validateMetaModelForStoreysHierarchy",value:function _validateMetaModelForStoreysHierarchy(){var level=arguments.length>0&&arguments[0]!==undefined?arguments[0]:0;var ctx=arguments.length>1?arguments[1]:undefined;var buildingNode=arguments.length>2?arguments[2]:undefined;// ctx = ctx || { // foundIFCBuildingStoreys: false @@ -27249,12 +27255,12 @@ _this149._sortNodes=cfg.sortNodes;_this149._pruneEmptyNodes=cfg.pruneEmptyNodes; // // errors.push("Can't build storeys hierarchy: no IfcBuildingStoreys found"); // } // } -return true;}},{key:"_createEnabledNodes",value:function _createEnabledNodes(){if(this._pruneEmptyNodes){this._findEmptyNodes();}switch(this._hierarchy){case"storeys":this._createStoreysNodes();if(this._rootNodes.length===0){this.error("Failed to build storeys hierarchy");}break;case"types":this._createTypesNodes();break;case"containment":default:this._createContainmentNodes();}if(this._sortNodes){this._doSortNodes();}this._synchNodesToEntities();this._createTrees();this.expandToDepth(this._autoExpandDepth);}},{key:"_createDisabledNodes",value:function _createDisabledNodes(){var rootNode=this._renderService.createRootNode();this._rootElement=rootNode;this._containerElement.appendChild(rootNode);var rootMetaObjects=this._viewer.metaScene.rootMetaObjects;for(var objectId in rootMetaObjects){var rootMetaObject=rootMetaObjects[objectId];var metaObjectType=rootMetaObject.type;var metaObjectName=rootMetaObject.name;var rootName=metaObjectName&&metaObjectName!==""&&metaObjectName!=="Undefined"&&metaObjectName!=="Default"?metaObjectName:metaObjectType;var childNode=this._renderService.createDisabledNodeElement(rootName);rootNode.appendChild(childNode);}}},{key:"_findEmptyNodes",value:function _findEmptyNodes(){var rootMetaObjects=this._viewer.metaScene.rootMetaObjects;for(var objectId in rootMetaObjects){this._findEmptyNodes2(rootMetaObjects[objectId]);}}},{key:"_findEmptyNodes2",value:function _findEmptyNodes2(metaObject){var countEntities=arguments.length>1&&arguments[1]!==undefined?arguments[1]:0;var viewer=this.viewer;var scene=viewer.scene;var children=metaObject.children;var objectId=metaObject.id;var entity=scene.objects[objectId];metaObject._countEntities=0;if(entity){metaObject._countEntities++;}if(children){for(var _i535=0,len=children.length;_i5351&&arguments[1]!==undefined?arguments[1]:0;var viewer=this.viewer;var scene=viewer.scene;var children=metaObject.children;var objectId=metaObject.id;var entity=scene.objects[objectId];metaObject._countEntities=0;if(entity){metaObject._countEntities++;}if(children){for(var _i537=0,len=children.length;_i537node2.aabb[idx]){return-1;}if(node1.aabb[idx]title2){return 1;}return 0;}},{key:"_synchNodesToEntities",value:function _synchNodesToEntities(){var objectIds=Object.keys(this.viewer.metaScene.metaObjects);var metaObjects=this._viewer.metaScene.metaObjects;var objects=this._viewer.scene.objects;for(var _i541=0,len=objectIds.length;_i541title2){return 1;}return 0;}},{key:"_synchNodesToEntities",value:function _synchNodesToEntities(){var objectIds=Object.keys(this.viewer.metaScene.metaObjects);var metaObjects=this._viewer.metaScene.metaObjects;var objects=this._viewer.scene.objects;for(var _i543=0,len=objectIds.length;_i5430){for(var _i544=0;_i5440){for(var _i546=0;_i546=this._maxTreeDepth){kdNode.objects=kdNode.objects||[];kdNode.objects.push(objectIdx);math.expandAABB3(kdNode.aabb,entityAABB);return;}if(kdNode.left){if(math.containsAABB3(kdNode.left.aabb,entityAABB)){this._insertEntityIntoKDTree(kdNode.left,entity,objectIdx,depth+1);return;}}if(kdNode.right){if(math.containsAABB3(kdNode.right.aabb,entityAABB)){this._insertEntityIntoKDTree(kdNode.right,entity,objectIdx,depth+1);return;}}var nodeAABB=kdNode.aabb;kdTreeDimLength[0]=nodeAABB[3]-nodeAABB[0];kdTreeDimLength[1]=nodeAABB[4]-nodeAABB[1];kdTreeDimLength[2]=nodeAABB[5]-nodeAABB[2];var dim=0;if(kdTreeDimLength[1]>kdTreeDimLength[dim]){dim=1;}if(kdTreeDimLength[2]>kdTreeDimLength[dim]){dim=2;}if(!kdNode.left){var aabbLeft=nodeAABB.slice();aabbLeft[dim+3]=(nodeAABB[dim]+nodeAABB[dim+3])/2.0;kdNode.left={aabb:aabbLeft,intersection:Frustum$1.INTERSECT};if(math.containsAABB3(aabbLeft,entityAABB)){this._insertEntityIntoKDTree(kdNode.left,entity,objectIdx,depth+1);return;}}if(!kdNode.right){var aabbRight=nodeAABB.slice();aabbRight[dim]=(nodeAABB[dim]+nodeAABB[dim+3])/2.0;kdNode.right={aabb:aabbRight,intersection:Frustum$1.INTERSECT};if(math.containsAABB3(aabbRight,entityAABB)){this._insertEntityIntoKDTree(kdNode.right,entity,objectIdx,depth+1);return;}}kdNode.objects=kdNode.objects||[];kdNode.objects.push(objectIdx);math.expandAABB3(kdNode.aabb,entityAABB);}},{key:"_visitKDNode",value:function _visitKDNode(kdNode){var intersects=arguments.length>1&&arguments[1]!==undefined?arguments[1]:Frustum$1.INTERSECT;if(intersects!==Frustum$1.INTERSECT&&kdNode.intersects===intersects){return;}if(intersects===Frustum$1.INTERSECT){intersects=frustumIntersectsAABB3(this._frustum,kdNode.aabb);kdNode.intersects=intersects;}var culled=intersects===Frustum$1.OUTSIDE;var objects=kdNode.objects;if(objects&&objects.length>0){for(var _i545=0,len=objects.length;_i545=this._maxTreeDepth){kdNode.objects=kdNode.objects||[];kdNode.objects.push(objectIdx);math.expandAABB3(kdNode.aabb,entityAABB);return;}if(kdNode.left){if(math.containsAABB3(kdNode.left.aabb,entityAABB)){this._insertEntityIntoKDTree(kdNode.left,entity,objectIdx,depth+1);return;}}if(kdNode.right){if(math.containsAABB3(kdNode.right.aabb,entityAABB)){this._insertEntityIntoKDTree(kdNode.right,entity,objectIdx,depth+1);return;}}var nodeAABB=kdNode.aabb;kdTreeDimLength[0]=nodeAABB[3]-nodeAABB[0];kdTreeDimLength[1]=nodeAABB[4]-nodeAABB[1];kdTreeDimLength[2]=nodeAABB[5]-nodeAABB[2];var dim=0;if(kdTreeDimLength[1]>kdTreeDimLength[dim]){dim=1;}if(kdTreeDimLength[2]>kdTreeDimLength[dim]){dim=2;}if(!kdNode.left){var aabbLeft=nodeAABB.slice();aabbLeft[dim+3]=(nodeAABB[dim]+nodeAABB[dim+3])/2.0;kdNode.left={aabb:aabbLeft,intersection:Frustum$1.INTERSECT};if(math.containsAABB3(aabbLeft,entityAABB)){this._insertEntityIntoKDTree(kdNode.left,entity,objectIdx,depth+1);return;}}if(!kdNode.right){var aabbRight=nodeAABB.slice();aabbRight[dim]=(nodeAABB[dim]+nodeAABB[dim+3])/2.0;kdNode.right={aabb:aabbRight,intersection:Frustum$1.INTERSECT};if(math.containsAABB3(aabbRight,entityAABB)){this._insertEntityIntoKDTree(kdNode.right,entity,objectIdx,depth+1);return;}}kdNode.objects=kdNode.objects||[];kdNode.objects.push(objectIdx);math.expandAABB3(kdNode.aabb,entityAABB);}},{key:"_visitKDNode",value:function _visitKDNode(kdNode){var intersects=arguments.length>1&&arguments[1]!==undefined?arguments[1]:Frustum$1.INTERSECT;if(intersects!==Frustum$1.INTERSECT&&kdNode.intersects===intersects){return;}if(intersects===Frustum$1.INTERSECT){intersects=frustumIntersectsAABB3(this._frustum,kdNode.aabb);kdNode.intersects=intersects;}var culled=intersects===Frustum$1.OUTSIDE;var objects=kdNode.objects;if(objects&&objects.length>0){for(var _i547=0,len=objects.length;_i547=0;){t[e]=0;}}var a=256,i=286,n=30,s=15,r=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),o=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),l=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),d=new Array(576);e(d);var _=new Array(60);e(_);var f=new Array(512);e(f);var c=new Array(256);e(c);var u=new Array(29);e(u);var w=new Array(n);function m(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length;}var b,g,p;function k(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e;}e(w);var v=function v(t){return t<256?f[t]:f[256+(t>>>7)];},y=function y(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255;},x=function x(t,e,a){t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<>>=1,a<<=1;}while(--e>0);return a>>>1;},E=function E(t,e,a){var i=new Array(16);var n,r,o=0;for(n=1;n<=s;n++){o=o+a[n-1]<<1,i[n]=o;}for(r=0;r<=e;r++){var _e2=t[2*r+1];0!==_e2&&(t[2*r]=A(i[_e2]++,_e2));}},R=function R(t){var e;for(e=0;e8?y(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0;},U=function U(t,e,a,i){var n=2*e,s=2*a;return t[n]>1;o>=1;o--){S(t,a,o);}h=r;do{o=t.heap[1],t.heap[1]=t.heap[t.heap_len--],S(t,a,1),l=t.heap[1],t.heap[--t.heap_max]=o,t.heap[--t.heap_max]=l,a[2*h]=a[2*o]+a[2*l],t.depth[h]=(t.depth[o]>=t.depth[l]?t.depth[o]:t.depth[l])+1,a[2*o+1]=a[2*l+1]=h,t.heap[1]=h++,S(t,a,1);}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,r=e.stat_desc.has_stree,o=e.stat_desc.extra_bits,l=e.stat_desc.extra_base,h=e.stat_desc.max_length;var d,_,f,c,u,w,m=0;for(c=0;c<=s;c++){t.bl_count[c]=0;}for(a[2*t.heap[t.heap_max]+1]=0,d=t.heap_max+1;d<573;d++){_=t.heap[d],c=a[2*a[2*_+1]+1]+1,c>h&&(c=h,m++),a[2*_+1]=c,_>i||(t.bl_count[c]++,u=0,_>=l&&(u=o[_-l]),w=a[2*_],t.opt_len+=w*(c+u),r&&(t.static_len+=w*(n[2*_+1]+u)));}if(0!==m){do{for(c=h-1;0===t.bl_count[c];){c--;}t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[h]--,m-=2;}while(m>0);for(c=h;0!==c;c--){for(_=t.bl_count[c];0!==_;){f=t.heap[--d],f>i||(a[2*f+1]!==c&&(t.opt_len+=(c-a[2*f+1])*a[2*f],a[2*f+1]=c),_--);}}}}(t,e),E(a,d,t.bl_count);},O=function O(t,e,a){var i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++){n=r,r=e[2*(i+1)+1],++o0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1){if(1&i&&0!==t.dyn_ltree[2*e])return 0;}if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e=3&&0===t.bl_tree[2*h[e]+1];e--){;}return t.opt_len+=3*(e+1)+5+5+4,e;}(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?L(t,e,i,n):4===t.strategy||r===s?(x(t,2+(n?1:0),3),D(t,d,_)):(x(t,4+(n?1:0),3),function(t,e,a,i){var n;for(x(t,e-257,5),x(t,a-1,5),x(t,i-4,4),n=0;n>=7;h>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(c[i]+a+1)]++,t.dyn_dtree[2*v(e)]++),t.sym_next===t.sym_end;},_tr_align:function _tr_align(t){x(t,2,3),z(t,256,d),function(t){16===t.bi_valid?(y(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8);}(t);}};var C=function C(t,e,a,i){var n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0;}while(--r);n%=65521,s%=65521;}return n|s<<16|0;};var M=new Uint32Array(function(){var t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++){t=1&t?3988292384^t>>>1:t>>>1;}e[a]=t;}return e;}());var H=function H(t,e,a,i){var n=M,s=i+a;t^=-1;for(var _a6=i;_a6>>8^n[255&(t^e[_a6])];}return-1^t;},j={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var P=B._tr_init,Y=B._tr_stored_block,G=B._tr_flush_block,X=B._tr_tally,W=B._tr_align,q=K.Z_NO_FLUSH,J=K.Z_PARTIAL_FLUSH,Q=K.Z_FULL_FLUSH,V=K.Z_FINISH,$=K.Z_BLOCK,tt=K.Z_OK,et=K.Z_STREAM_END,at=K.Z_STREAM_ERROR,it=K.Z_DATA_ERROR,nt=K.Z_BUF_ERROR,st=K.Z_DEFAULT_COMPRESSION,rt=K.Z_FILTERED,ot=K.Z_HUFFMAN_ONLY,lt=K.Z_RLE,ht=K.Z_FIXED,dt=K.Z_DEFAULT_STRATEGY,_t=K.Z_UNKNOWN,ft=K.Z_DEFLATED,ct=258,ut=262,wt=42,mt=113,bt=666,gt=function gt(t,e){return t.msg=j[e],e;},pt=function pt(t){return 2*t-(t>4?9:0);},kt=function kt(t){var e=t.length;for(;--e>=0;){t[e]=0;}},vt=function vt(t){var e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0;}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0;}while(--e);};var yt=function yt(t,e,a){return(e<t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0));},zt=function zt(t,e){G(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,xt(t.strm);},At=function At(t,e){t.pending_buf[t.pending++]=e;},Et=function Et(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e;},Rt=function Rt(t,e,a,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=C(t.adler,e,n,a):2===t.state.wrap&&(t.adler=H(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n);},Zt=function Zt(t,e){var a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;var l=t.strstart>t.w_size-ut?t.strstart-(t.w_size-ut):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+ct;var c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r];}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead;},Ut=function Ut(t){var e=t.w_size;var a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ut)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),vt(t),i+=e),0===t.strm.avail_in)break;if(a=Rt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=yt(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=yt(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3));){;}}while(t.lookaheadt.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,xt(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(Rt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a);}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(Rt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===V)&&e!==q&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===V&&0===t.strm.avail_in&&a===i?1:0,Y(t,t.block_start,a,r),t.block_start+=a,xt(t.strm)),r?3:1);},Dt=function Dt(t,e){var a,i;for(;;){if(t.lookahead=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-ut&&(t.match_length=Zt(t,a)),t.match_length>=3){if(i=X(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;}while(0!=--t.match_length);t.strstart++;}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=yt(t,t.ins_h,t.window[t.strstart+1]);}else i=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;},Tt=function Tt(t,e){var a,i,n;for(;;){if(t.lookahead=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=X(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(zt(t,!1),0===t.strm.avail_out))return 1;}else if(t.match_available){if(i=X(t,0,t.window[t.strstart-1]),i&&zt(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1;}else t.match_available=1,t.strstart++,t.lookahead--;}return t.match_available&&(i=X(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;};function Ot(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n;}var It=[new Ot(0,0,0,0,St),new Ot(4,4,8,4,Dt),new Ot(4,5,16,8,Dt),new Ot(4,6,32,32,Dt),new Ot(4,4,16,16,Tt),new Ot(8,16,32,32,Tt),new Ot(8,16,128,128,Tt),new Ot(8,32,128,256,Tt),new Ot(32,128,258,1024,Tt),new Ot(32,258,258,4096,Tt)];function Ft(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ft,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),kt(this.dyn_ltree),kt(this.dyn_dtree),kt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),kt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),kt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}var Lt=function Lt(t){if(!t)return 1;var e=t.state;return!e||e.strm!==t||e.status!==wt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==mt&&e.status!==bt?1:0;},Nt=function Nt(t){if(Lt(t))return gt(t,at);t.total_in=t.total_out=0,t.data_type=_t;var e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?wt:mt,t.adler=2===e.wrap?0:1,e.last_flush=-2,P(e),tt;},Bt=function Bt(t){var e=Nt(t);var a;return e===tt&&((a=t.state).window_size=2*a.w_size,kt(a.head),a.max_lazy_match=It[a.level].max_lazy,a.good_match=It[a.level].good_length,a.nice_match=It[a.level].nice_length,a.max_chain_length=It[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e;},Ct=function Ct(t,e,a,i,n,s){if(!t)return at;var r=1;if(e===st&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ft||i<8||i>15||e<0||e>9||s<0||s>ht||8===i&&1!==r)return gt(t,at);8===i&&(i=9);var o=new Ft();return t.state=o,o.strm=t,o.status=wt,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<$||e<0)return t?gt(t,at):at;var a=t.state;if(!t.output||0!==t.avail_in&&!t.input||a.status===bt&&e!==V)return gt(t,0===t.avail_out?nt:at);var i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(xt(t),0===t.avail_out)return a.last_flush=-1,tt;}else if(0===t.avail_in&&pt(e)<=pt(i)&&e!==V)return gt(t,nt);if(a.status===bt&&0!==t.avail_in)return gt(t,nt);if(a.status===wt&&0===a.wrap&&(a.status=mt),a.status===wt){var _e3=ft+(a.w_bits-8<<4)<<8,_i546=-1;if(_i546=a.strategy>=ot||a.level<2?0:a.level<6?1:6===a.level?2:3,_e3|=_i546<<6,0!==a.strstart&&(_e3|=32),_e3+=31-_e3%31,Et(a,_e3),0!==a.strstart&&(Et(a,t.adler>>>16),Et(a,65535&t.adler)),t.adler=1,a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;}if(57===a.status)if(t.adler=0,At(a,31),At(a,139),At(a,8),a.gzhead)At(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),At(a,255&a.gzhead.time),At(a,a.gzhead.time>>8&255),At(a,a.gzhead.time>>16&255),At(a,a.gzhead.time>>24&255),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(At(a,255&a.gzhead.extra.length),At(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=H(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(At(a,0),At(a,0),At(a,0),At(a,0),At(a,0),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,3),a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;if(69===a.status){if(a.gzhead.extra){var _e4=a.pending,_i547=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+_i547>a.pending_buf_size;){var _n3=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+_n3),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>_e4&&(t.adler=H(t.adler,a.pending_buf,a.pending-_e4,_e4)),a.gzindex+=_n3,xt(t),0!==a.pending)return a.last_flush=-1,tt;_e4=0,_i547-=_n3;}var _n2=new Uint8Array(a.gzhead.extra);a.pending_buf.set(_n2.subarray(a.gzindex,a.gzindex+_i547),a.pending),a.pending+=_i547,a.gzhead.hcrc&&a.pending>_e4&&(t.adler=H(t.adler,a.pending_buf,a.pending-_e4,_e4)),a.gzindex=0;}a.status=73;}if(73===a.status){if(a.gzhead.name){var _e5,_i548=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>_i548&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i548,_i548)),xt(t),0!==a.pending)return a.last_flush=-1,tt;_i548=0;}_e5=a.gzindex_i548&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i548,_i548)),a.gzindex=0;}a.status=91;}if(91===a.status){if(a.gzhead.comment){var _e6,_i549=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>_i549&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i549,_i549)),xt(t),0!==a.pending)return a.last_flush=-1,tt;_i549=0;}_e6=a.gzindex_i549&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i549,_i549));}a.status=103;}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(xt(t),0!==a.pending))return a.last_flush=-1,tt;At(a,255&t.adler),At(a,t.adler>>8&255),t.adler=0;}if(a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;}if(0!==t.avail_in||0!==a.lookahead||e!==q&&a.status!==bt){var _i550=0===a.level?St(a,e):a.strategy===ot?function(t,e){var a;for(;;){if(0===t.lookahead&&(Ut(t),0===t.lookahead)){if(e===q)return 1;break;}if(t.match_length=0,a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;}(a,e):a.strategy===lt?function(t,e){var a,i,n,s;var r=t.window;for(;;){if(t.lookahead<=ct){if(Ut(t),t.lookahead<=ct&&e===q)return 1;if(0===t.lookahead)break;}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+ct;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead);}if(t.match_length>=3?(a=X(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;}(a,e):It[a.level].func(a,e);if(3!==_i550&&4!==_i550||(a.status=bt),1===_i550||3===_i550)return 0===t.avail_out&&(a.last_flush=-1),tt;if(2===_i550&&(e===J?W(a):e!==$&&(Y(a,0,0,!1),e===Q&&(kt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),xt(t),0===t.avail_out))return a.last_flush=-1,tt;}return e!==V?tt:a.wrap<=0?et:(2===a.wrap?(At(a,255&t.adler),At(a,t.adler>>8&255),At(a,t.adler>>16&255),At(a,t.adler>>24&255),At(a,255&t.total_in),At(a,t.total_in>>8&255),At(a,t.total_in>>16&255),At(a,t.total_in>>24&255)):(Et(a,t.adler>>>16),Et(a,65535&t.adler)),xt(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?tt:et);},deflateEnd:function deflateEnd(t){if(Lt(t))return at;var e=t.state.status;return t.state=null,e===mt?gt(t,it):tt;},deflateSetDictionary:function deflateSetDictionary(t,e){var a=e.length;if(Lt(t))return at;var i=t.state,n=i.wrap;if(2===n||1===n&&i.status!==wt||i.lookahead)return at;if(1===n&&(t.adler=C(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(kt(i.head),i.strstart=0,i.block_start=0,i.insert=0);var _t2=new Uint8Array(i.w_size);_t2.set(e.subarray(a-i.w_size,a),0),e=_t2,a=i.w_size;}var s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,Ut(i);i.lookahead>=3;){var _t3=i.strstart,_e7=i.lookahead-2;do{i.ins_h=yt(i,i.ins_h,i.window[_t3+3-1]),i.prev[_t3&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=_t3,_t3++;}while(--_e7);i.strstart=_t3,i.lookahead=2,Ut(i);}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,tt;},deflateInfo:"pako deflate (from Nodeca project)"};var Ht=function Ht(t,e){return Object.prototype.hasOwnProperty.call(t,e);};var jt=function jt(t){var e=Array.prototype.slice.call(arguments,1);for(;e.length;){var _a7=e.shift();if(_a7){if("object"!=_typeof(_a7))throw new TypeError(_a7+"must be non-object");for(var _e8 in _a7){Ht(_a7,_e8)&&(t[_e8]=_a7[_e8]);}}}return t;},Kt=function Kt(t){var e=0;for(var _a8=0,_i551=t.length;_a8<_i551;_a8++){e+=t[_a8].length;}var a=new Uint8Array(e);for(var _e9=0,_i552=0,_n4=t.length;_e9<_n4;_e9++){var _n5=t[_e9];a.set(_n5,_i552),_i552+=_n5.length;}return a;};var Pt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1));}catch(t){Pt=!1;}var Yt=new Uint8Array(256);for(var _t4=0;_t4<256;_t4++){Yt[_t4]=_t4>=252?6:_t4>=248?5:_t4>=240?4:_t4>=224?3:_t4>=192?2:1;}Yt[254]=Yt[254]=1;var Gt=function Gt(t){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);var e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);}return e;},Xt=function Xt(t,e){var a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,e));var i,n;var s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=_r6-1;else{for(_e10&=2===_r6?31:3===_r6?15:7;_r6>1&&i1?s[n++]=65533:_e10<65536?s[n++]=_e10:(_e10-=65536,s[n++]=55296|_e10>>10&1023,s[n++]=56320|1023&_e10);}}return function(t,e){if(e<65534&&t.subarray&&Pt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));var a="";for(var _i553=0;_i553t.length&&(e=t.length);var a=e-1;for(;a>=0&&128==(192&t[a]);){a--;}return a<0||0===a?e:a+Yt[t[a]]>e?a:e;};var qt=function qt(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;};var Jt=Object.prototype.toString,Qt=K.Z_NO_FLUSH,Vt=K.Z_SYNC_FLUSH,$t=K.Z_FULL_FLUSH,te=K.Z_FINISH,ee=K.Z_OK,ae=K.Z_STREAM_END,ie=K.Z_DEFAULT_COMPRESSION,ne=K.Z_DEFAULT_STRATEGY,se=K.Z_DEFLATED;function re(t){this.options=jt({level:ie,method:se,chunkSize:16384,windowBits:15,memLevel:8,strategy:ne},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt(),this.strm.avail_out=0;var a=Mt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==ee)throw new Error(j[a]);if(e.header&&Mt.deflateSetHeader(this.strm,e.header),e.dictionary){var _t5;if(_t5="string"==typeof e.dictionary?Gt(e.dictionary):"[object ArrayBuffer]"===Jt.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Mt.deflateSetDictionary(this.strm,_t5),a!==ee)throw new Error(j[a]);this._dict_set=!0;}}function oe(t,e){var a=new re(e);if(a.push(t,!0),a.err)throw a.msg||j[a.err];return a.result;}re.prototype.push=function(t,e){var a=this.strm,i=this.options.chunkSize;var n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?te:Qt,"string"==typeof t?a.input=Gt(t):"[object ArrayBuffer]"===Jt.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===Vt||s===$t)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Mt.deflate(a,s),n===ae)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Mt.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===ee;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break;}else this.onData(a.output);}}return!0;},re.prototype.onData=function(t){this.chunks.push(t);},re.prototype.onEnd=function(t){t===ee&&(this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg;};var le={Deflate:re,deflate:oe,deflateRaw:function deflateRaw(t,e){return(e=e||{}).raw=!0,oe(t,e);},gzip:function gzip(t,e){return(e=e||{}).gzip=!0,oe(t,e);},constants:K};var he=16209;var de=function de(t,e){var a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;var E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg="invalid distance too far back",E.mode=he;break t;}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=he;break t;}if(y=0,x=_,0===d){if(y+=l-p,p2;){A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;}k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]));}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3;}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]));}break;}}break;}}while(a>3,a-=k,c-=k<<3,f&=(1<=1&&0===E[g];g--){;}if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<_e;w++){R[w+1]=R[w]+E[w];}for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0;}while(0!==d);for(h=1<>=1;}if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]];}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0;}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0;};var be=K.Z_FINISH,ge=K.Z_BLOCK,pe=K.Z_TREES,ke=K.Z_OK,ve=K.Z_STREAM_END,ye=K.Z_NEED_DICT,xe=K.Z_STREAM_ERROR,ze=K.Z_DATA_ERROR,Ae=K.Z_MEM_ERROR,Ee=K.Z_BUF_ERROR,Re=K.Z_DEFLATED,Ze=16180,Ue=16190,Se=16191,De=16192,Te=16194,Oe=16199,Ie=16200,Fe=16206,Le=16209,Ne=function Ne(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);};function Be(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}var Ce=function Ce(t){if(!t)return 1;var e=t.state;return!e||e.strm!==t||e.mode16211?1:0;},Me=function Me(t){if(Ce(t))return xe;var e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=Ze,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ke;},He=function He(t){if(Ce(t))return xe;var e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,Me(t);},je=function je(t,e){var a;if(Ce(t))return xe;var i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?xe:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,He(t));},Ke=function Ke(t,e){if(!t)return xe;var a=new Be();t.state=a,a.strm=t,a.window=null,a.mode=Ze;var i=je(t,e);return i!==ke&&(t.state=null),i;};var Pe,Ye,Ge=!0;var Xe=function Xe(t){if(Ge){Pe=new Int32Array(512),Ye=new Int32Array(32);var _e11=0;for(;_e11<144;){t.lens[_e11++]=8;}for(;_e11<256;){t.lens[_e11++]=9;}for(;_e11<280;){t.lens[_e11++]=7;}for(;_e11<288;){t.lens[_e11++]=8;}for(me(1,t.lens,0,288,Pe,0,t.work,{bits:9}),_e11=0;_e11<32;){t.lens[_e11++]=5;}me(2,t.lens,0,32,Ye,0,t.work,{bits:5}),Ge=!1;}t.lencode=Pe,t.lenbits=9,t.distcode=Ye,t.distbits=5;},We=function We(t,e,a,i){var n;var s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,a.check=H(a.check,A,2,0),h=0,d=0,a.mode=16181;break;}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=Le;break;}if((15&h)!==Re){t.msg="unknown compression method",a.mode=Le;break;}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=Le;break;}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=H(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0;}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=H(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y));}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=Se;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=Fe;break;}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Xe(a),a.mode=Oe,e===pe){h>>>=2,d-=2;break t;}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=Le;}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=Le;break;}if(a.length=65535&h,h=0,d=0,a.mode=Te,e===pe)break t;case Te:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break;}a.mode=Se;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=Le;break;}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3;}for(;a.have<19;){a.lens[Z[a.have++]]=0;}if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=me(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=Le;break;}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=Le;break;}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2;}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3;}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7;}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=Le;break;}for(;c--;){a.lens[a.have++]=y;}}}if(a.mode===Le)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=Le;break;}if(a.lenbits=9,E={bits:a.lenbits},x=me(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=Le;break;}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=me(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=Le;break;}if(a.mode=Oe,e===pe)break t;case Oe:a.mode=Ie;case Ie:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,de(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,a.mode===Se&&(a.back=-1);break;}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p;}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break;}if(32&b){a.back=-1,a.mode=Se;break;}if(64&b){t.msg="invalid literal/length code",a.mode=Le;break;}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra;}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p;}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=Le;break;}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra;}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=Le;break;}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=Le;break;}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window;}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++];}while(--c);0===a.length&&(a.mode=Ie);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=Ie;break;case Fe:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt(),this.strm.avail_out=0;var a=qe.inflateInit2(this.strm,e.windowBits);if(a!==ta)throw new Error(j[a]);if(this.header=new Je(),qe.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Gt(e.dictionary):"[object ArrayBuffer]"===Qe.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=qe.inflateSetDictionary(this.strm,e.dictionary),a!==ta)))throw new Error(j[a]);}function oa(t,e){var a=new ra(e);if(a.push(t),a.err)throw a.msg||j[a.err];return a.result;}ra.prototype.push=function(t,e){var a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;var s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?$e:Ve,"[object ArrayBuffer]"===Qe.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=qe.inflate(a,r),s===aa&&n&&(s=qe.inflateSetDictionary(a,n),s===ta?s=qe.inflate(a,r):s===na&&(s=aa));a.avail_in>0&&s===ea&&a.state.wrap>0&&0!==t[a.next_in];){qe.inflateReset(a),s=qe.inflate(a,r);}switch(s){case ia:case na:case aa:case sa:return this.onEnd(s),this.ended=!0,!1;}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===ea))if("string"===this.options.to){var _t6=Wt(a.output,a.next_out),_e12=a.next_out-_t6,_n6=Xt(a.output,_t6);a.next_out=_e12,a.avail_out=i-_e12,_e12&&a.output.set(a.output.subarray(_t6,_t6+_e12),0),this.onData(_n6);}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==ta||0!==o){if(s===ea)return s=qe.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break;}}return!0;},ra.prototype.onData=function(t){this.chunks.push(t);},ra.prototype.onEnd=function(t){t===ta&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg;};var la={Inflate:ra,inflate:oa,inflateRaw:function inflateRaw(t,e){return(e=e||{}).raw=!0,oa(t,e);},ungzip:oa,constants:K};var ha=le.Deflate,da=le.deflate,_a=le.deflateRaw,fa=le.gzip,ca=la.Inflate,ua=la.inflate,wa=la.inflateRaw,ma=la.ungzip;var ba=ha,ga=da,pa=_a,ka=fa,va=ca,ya=ua,xa=wa,za=ma,Aa=K,Ea={Deflate:ba,deflate:ga,deflateRaw:pa,gzip:ka,Inflate:va,inflate:ya,inflateRaw:xa,ungzip:za,constants:Aa};t.Deflate=ba,t.Inflate=va,t.constants=Aa,t["default"]=Ea,t.deflate=ga,t.deflateRaw=pa,t.gzip=ka,t.inflate=ya,t.inflateRaw=xa,t.ungzip=za,Object.defineProperty(t,"__esModule",{value:!0});});var p=/*#__PURE__*/Object.freeze({__proto__:null});/* +var isBase64=!!dataUriRegexResult[2];var data=dataUriRegexResult[3];data=window.decodeURIComponent(data);if(isBase64){data=window.atob(data);}try{var buffer=new ArrayBuffer(data.length);var view=new Uint8Array(buffer);for(var i=0;i=0;){t[e]=0;}}var a=256,i=286,n=30,s=15,r=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),o=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),l=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),h=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),d=new Array(576);e(d);var _=new Array(60);e(_);var f=new Array(512);e(f);var c=new Array(256);e(c);var u=new Array(29);e(u);var w=new Array(n);function m(t,e,a,i,n){this.static_tree=t,this.extra_bits=e,this.extra_base=a,this.elems=i,this.max_length=n,this.has_stree=t&&t.length;}var b,g,p;function k(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e;}e(w);var v=function v(t){return t<256?f[t]:f[256+(t>>>7)];},y=function y(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255;},x=function x(t,e,a){t.bi_valid>16-a?(t.bi_buf|=e<>16-t.bi_valid,t.bi_valid+=a-16):(t.bi_buf|=e<>>=1,a<<=1;}while(--e>0);return a>>>1;},E=function E(t,e,a){var i=new Array(16);var n,r,o=0;for(n=1;n<=s;n++){o=o+a[n-1]<<1,i[n]=o;}for(r=0;r<=e;r++){var _e2=t[2*r+1];0!==_e2&&(t[2*r]=A(i[_e2]++,_e2));}},R=function R(t){var e;for(e=0;e8?y(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0;},U=function U(t,e,a,i){var n=2*e,s=2*a;return t[n]>1;o>=1;o--){S(t,a,o);}h=r;do{o=t.heap[1],t.heap[1]=t.heap[t.heap_len--],S(t,a,1),l=t.heap[1],t.heap[--t.heap_max]=o,t.heap[--t.heap_max]=l,a[2*h]=a[2*o]+a[2*l],t.depth[h]=(t.depth[o]>=t.depth[l]?t.depth[o]:t.depth[l])+1,a[2*o+1]=a[2*l+1]=h,t.heap[1]=h++,S(t,a,1);}while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],function(t,e){var a=e.dyn_tree,i=e.max_code,n=e.stat_desc.static_tree,r=e.stat_desc.has_stree,o=e.stat_desc.extra_bits,l=e.stat_desc.extra_base,h=e.stat_desc.max_length;var d,_,f,c,u,w,m=0;for(c=0;c<=s;c++){t.bl_count[c]=0;}for(a[2*t.heap[t.heap_max]+1]=0,d=t.heap_max+1;d<573;d++){_=t.heap[d],c=a[2*a[2*_+1]+1]+1,c>h&&(c=h,m++),a[2*_+1]=c,_>i||(t.bl_count[c]++,u=0,_>=l&&(u=o[_-l]),w=a[2*_],t.opt_len+=w*(c+u),r&&(t.static_len+=w*(n[2*_+1]+u)));}if(0!==m){do{for(c=h-1;0===t.bl_count[c];){c--;}t.bl_count[c]--,t.bl_count[c+1]+=2,t.bl_count[h]--,m-=2;}while(m>0);for(c=h;0!==c;c--){for(_=t.bl_count[c];0!==_;){f=t.heap[--d],f>i||(a[2*f+1]!==c&&(t.opt_len+=(c-a[2*f+1])*a[2*f],a[2*f+1]=c),_--);}}}}(t,e),E(a,d,t.bl_count);},O=function O(t,e,a){var i,n,s=-1,r=e[1],o=0,l=7,h=4;for(0===r&&(l=138,h=3),e[2*(a+1)+1]=65535,i=0;i<=a;i++){n=r,r=e[2*(i+1)+1],++o0?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1){if(1&i&&0!==t.dyn_ltree[2*e])return 0;}if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return 1;for(e=32;e=3&&0===t.bl_tree[2*h[e]+1];e--){;}return t.opt_len+=3*(e+1)+5+5+4,e;}(t),s=t.opt_len+3+7>>>3,r=t.static_len+3+7>>>3,r<=s&&(s=r)):s=r=i+5,i+4<=s&&-1!==e?L(t,e,i,n):4===t.strategy||r===s?(x(t,2+(n?1:0),3),D(t,d,_)):(x(t,4+(n?1:0),3),function(t,e,a,i){var n;for(x(t,e-257,5),x(t,a-1,5),x(t,i-4,4),n=0;n>=7;h>8,t.pending_buf[t.sym_buf+t.sym_next++]=i,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(c[i]+a+1)]++,t.dyn_dtree[2*v(e)]++),t.sym_next===t.sym_end;},_tr_align:function _tr_align(t){x(t,2,3),z(t,256,d),function(t){16===t.bi_valid?(y(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8);}(t);}};var C=function C(t,e,a,i){var n=65535&t|0,s=t>>>16&65535|0,r=0;for(;0!==a;){r=a>2e3?2e3:a,a-=r;do{n=n+e[i++]|0,s=s+n|0;}while(--r);n%=65521,s%=65521;}return n|s<<16|0;};var M=new Uint32Array(function(){var t,e=[];for(var a=0;a<256;a++){t=a;for(var i=0;i<8;i++){t=1&t?3988292384^t>>>1:t>>>1;}e[a]=t;}return e;}());var H=function H(t,e,a,i){var n=M,s=i+a;t^=-1;for(var _a6=i;_a6>>8^n[255&(t^e[_a6])];}return-1^t;},j={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},K={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};var P=B._tr_init,Y=B._tr_stored_block,G=B._tr_flush_block,X=B._tr_tally,W=B._tr_align,q=K.Z_NO_FLUSH,J=K.Z_PARTIAL_FLUSH,Q=K.Z_FULL_FLUSH,V=K.Z_FINISH,$=K.Z_BLOCK,tt=K.Z_OK,et=K.Z_STREAM_END,at=K.Z_STREAM_ERROR,it=K.Z_DATA_ERROR,nt=K.Z_BUF_ERROR,st=K.Z_DEFAULT_COMPRESSION,rt=K.Z_FILTERED,ot=K.Z_HUFFMAN_ONLY,lt=K.Z_RLE,ht=K.Z_FIXED,dt=K.Z_DEFAULT_STRATEGY,_t=K.Z_UNKNOWN,ft=K.Z_DEFLATED,ct=258,ut=262,wt=42,mt=113,bt=666,gt=function gt(t,e){return t.msg=j[e],e;},pt=function pt(t){return 2*t-(t>4?9:0);},kt=function kt(t){var e=t.length;for(;--e>=0;){t[e]=0;}},vt=function vt(t){var e,a,i,n=t.w_size;e=t.hash_size,i=e;do{a=t.head[--i],t.head[i]=a>=n?a-n:0;}while(--e);e=n,i=e;do{a=t.prev[--i],t.prev[i]=a>=n?a-n:0;}while(--e);};var yt=function yt(t,e,a){return(e<t.avail_out&&(a=t.avail_out),0!==a&&(t.output.set(e.pending_buf.subarray(e.pending_out,e.pending_out+a),t.next_out),t.next_out+=a,e.pending_out+=a,t.total_out+=a,t.avail_out-=a,e.pending-=a,0===e.pending&&(e.pending_out=0));},zt=function zt(t,e){G(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,xt(t.strm);},At=function At(t,e){t.pending_buf[t.pending++]=e;},Et=function Et(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e;},Rt=function Rt(t,e,a,i){var n=t.avail_in;return n>i&&(n=i),0===n?0:(t.avail_in-=n,e.set(t.input.subarray(t.next_in,t.next_in+n),a),1===t.state.wrap?t.adler=C(t.adler,e,n,a):2===t.state.wrap&&(t.adler=H(t.adler,e,n,a)),t.next_in+=n,t.total_in+=n,n);},Zt=function Zt(t,e){var a,i,n=t.max_chain_length,s=t.strstart,r=t.prev_length,o=t.nice_match;var l=t.strstart>t.w_size-ut?t.strstart-(t.w_size-ut):0,h=t.window,d=t.w_mask,_=t.prev,f=t.strstart+ct;var c=h[s+r-1],u=h[s+r];t.prev_length>=t.good_match&&(n>>=2),o>t.lookahead&&(o=t.lookahead);do{if(a=e,h[a+r]===u&&h[a+r-1]===c&&h[a]===h[s]&&h[++a]===h[s+1]){s+=2,a++;do{}while(h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&h[++s]===h[++a]&&sr){if(t.match_start=e,r=i,i>=o)break;c=h[s+r-1],u=h[s+r];}}}while((e=_[e&d])>l&&0!=--n);return r<=t.lookahead?r:t.lookahead;},Ut=function Ut(t){var e=t.w_size;var a,i,n;do{if(i=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-ut)&&(t.window.set(t.window.subarray(e,e+e-i),0),t.match_start-=e,t.strstart-=e,t.block_start-=e,t.insert>t.strstart&&(t.insert=t.strstart),vt(t),i+=e),0===t.strm.avail_in)break;if(a=Rt(t.strm,t.window,t.strstart+t.lookahead,i),t.lookahead+=a,t.lookahead+t.insert>=3)for(n=t.strstart-t.insert,t.ins_h=t.window[n],t.ins_h=yt(t,t.ins_h,t.window[n+1]);t.insert&&(t.ins_h=yt(t,t.ins_h,t.window[n+3-1]),t.prev[n&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=n,n++,t.insert--,!(t.lookahead+t.insert<3));){;}}while(t.lookaheadt.w_size?t.w_size:t.pending_buf_size-5,r=0,o=t.strm.avail_in;do{if(a=65535,n=t.bi_valid+42>>3,t.strm.avail_outi+t.strm.avail_in&&(a=i+t.strm.avail_in),a>n&&(a=n),a>8,t.pending_buf[t.pending-2]=~a,t.pending_buf[t.pending-1]=~a>>8,xt(t.strm),i&&(i>a&&(i=a),t.strm.output.set(t.window.subarray(t.block_start,t.block_start+i),t.strm.next_out),t.strm.next_out+=i,t.strm.avail_out-=i,t.strm.total_out+=i,t.block_start+=i,a-=i),a&&(Rt(t.strm,t.strm.output,t.strm.next_out,a),t.strm.next_out+=a,t.strm.avail_out-=a,t.strm.total_out+=a);}while(0===r);return o-=t.strm.avail_in,o&&(o>=t.w_size?(t.matches=2,t.window.set(t.strm.input.subarray(t.strm.next_in-t.w_size,t.strm.next_in),0),t.strstart=t.w_size,t.insert=t.strstart):(t.window_size-t.strstart<=o&&(t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,t.insert>t.strstart&&(t.insert=t.strstart)),t.window.set(t.strm.input.subarray(t.strm.next_in-o,t.strm.next_in),t.strstart),t.strstart+=o,t.insert+=o>t.w_size-t.insert?t.w_size-t.insert:o),t.block_start=t.strstart),t.high_watern&&t.block_start>=t.w_size&&(t.block_start-=t.w_size,t.strstart-=t.w_size,t.window.set(t.window.subarray(t.w_size,t.w_size+t.strstart),0),t.matches<2&&t.matches++,n+=t.w_size,t.insert>t.strstart&&(t.insert=t.strstart)),n>t.strm.avail_in&&(n=t.strm.avail_in),n&&(Rt(t.strm,t.window,t.strstart,n),t.strstart+=n,t.insert+=n>t.w_size-t.insert?t.w_size-t.insert:n),t.high_water>3,n=t.pending_buf_size-n>65535?65535:t.pending_buf_size-n,s=n>t.w_size?t.w_size:n,i=t.strstart-t.block_start,(i>=s||(i||e===V)&&e!==q&&0===t.strm.avail_in&&i<=n)&&(a=i>n?n:i,r=e===V&&0===t.strm.avail_in&&a===i?1:0,Y(t,t.block_start,a,r),t.block_start+=a,xt(t.strm)),r?3:1);},Dt=function Dt(t,e){var a,i;for(;;){if(t.lookahead=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==a&&t.strstart-a<=t.w_size-ut&&(t.match_length=Zt(t,a)),t.match_length>=3){if(i=X(t,t.strstart-t.match_start,t.match_length-3),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=3){t.match_length--;do{t.strstart++,t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart;}while(0!=--t.match_length);t.strstart++;}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=yt(t,t.ins_h,t.window[t.strstart+1]);}else i=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(i&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;},Tt=function Tt(t,e){var a,i,n;for(;;){if(t.lookahead=3&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=2,0!==a&&t.prev_length4096)&&(t.match_length=2)),t.prev_length>=3&&t.match_length<=t.prev_length){n=t.strstart+t.lookahead-3,i=X(t,t.strstart-1-t.prev_match,t.prev_length-3),t.lookahead-=t.prev_length-1,t.prev_length-=2;do{++t.strstart<=n&&(t.ins_h=yt(t,t.ins_h,t.window[t.strstart+3-1]),a=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart);}while(0!=--t.prev_length);if(t.match_available=0,t.match_length=2,t.strstart++,i&&(zt(t,!1),0===t.strm.avail_out))return 1;}else if(t.match_available){if(i=X(t,0,t.window[t.strstart-1]),i&&zt(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return 1;}else t.match_available=1,t.strstart++,t.lookahead--;}return t.match_available&&(i=X(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<2?t.strstart:2,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;};function Ot(t,e,a,i,n){this.good_length=t,this.max_lazy=e,this.nice_length=a,this.max_chain=i,this.func=n;}var It=[new Ot(0,0,0,0,St),new Ot(4,4,8,4,Dt),new Ot(4,5,16,8,Dt),new Ot(4,6,32,32,Dt),new Ot(4,4,16,16,Tt),new Ot(8,16,32,32,Tt),new Ot(8,16,128,128,Tt),new Ot(8,32,128,256,Tt),new Ot(32,128,258,1024,Tt),new Ot(32,258,258,4096,Tt)];function Ft(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ft,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),kt(this.dyn_ltree),kt(this.dyn_dtree),kt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),kt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),kt(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}var Lt=function Lt(t){if(!t)return 1;var e=t.state;return!e||e.strm!==t||e.status!==wt&&57!==e.status&&69!==e.status&&73!==e.status&&91!==e.status&&103!==e.status&&e.status!==mt&&e.status!==bt?1:0;},Nt=function Nt(t){if(Lt(t))return gt(t,at);t.total_in=t.total_out=0,t.data_type=_t;var e=t.state;return e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=2===e.wrap?57:e.wrap?wt:mt,t.adler=2===e.wrap?0:1,e.last_flush=-2,P(e),tt;},Bt=function Bt(t){var e=Nt(t);var a;return e===tt&&((a=t.state).window_size=2*a.w_size,kt(a.head),a.max_lazy_match=It[a.level].max_lazy,a.good_match=It[a.level].good_length,a.nice_match=It[a.level].nice_length,a.max_chain_length=It[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=2,a.match_available=0,a.ins_h=0),e;},Ct=function Ct(t,e,a,i,n,s){if(!t)return at;var r=1;if(e===st&&(e=6),i<0?(r=0,i=-i):i>15&&(r=2,i-=16),n<1||n>9||a!==ft||i<8||i>15||e<0||e>9||s<0||s>ht||8===i&&1!==r)return gt(t,at);8===i&&(i=9);var o=new Ft();return t.state=o,o.strm=t,o.status=wt,o.wrap=r,o.gzhead=null,o.w_bits=i,o.w_size=1<$||e<0)return t?gt(t,at):at;var a=t.state;if(!t.output||0!==t.avail_in&&!t.input||a.status===bt&&e!==V)return gt(t,0===t.avail_out?nt:at);var i=a.last_flush;if(a.last_flush=e,0!==a.pending){if(xt(t),0===t.avail_out)return a.last_flush=-1,tt;}else if(0===t.avail_in&&pt(e)<=pt(i)&&e!==V)return gt(t,nt);if(a.status===bt&&0!==t.avail_in)return gt(t,nt);if(a.status===wt&&0===a.wrap&&(a.status=mt),a.status===wt){var _e3=ft+(a.w_bits-8<<4)<<8,_i548=-1;if(_i548=a.strategy>=ot||a.level<2?0:a.level<6?1:6===a.level?2:3,_e3|=_i548<<6,0!==a.strstart&&(_e3|=32),_e3+=31-_e3%31,Et(a,_e3),0!==a.strstart&&(Et(a,t.adler>>>16),Et(a,65535&t.adler)),t.adler=1,a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;}if(57===a.status)if(t.adler=0,At(a,31),At(a,139),At(a,8),a.gzhead)At(a,(a.gzhead.text?1:0)+(a.gzhead.hcrc?2:0)+(a.gzhead.extra?4:0)+(a.gzhead.name?8:0)+(a.gzhead.comment?16:0)),At(a,255&a.gzhead.time),At(a,a.gzhead.time>>8&255),At(a,a.gzhead.time>>16&255),At(a,a.gzhead.time>>24&255),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,255&a.gzhead.os),a.gzhead.extra&&a.gzhead.extra.length&&(At(a,255&a.gzhead.extra.length),At(a,a.gzhead.extra.length>>8&255)),a.gzhead.hcrc&&(t.adler=H(t.adler,a.pending_buf,a.pending,0)),a.gzindex=0,a.status=69;else if(At(a,0),At(a,0),At(a,0),At(a,0),At(a,0),At(a,9===a.level?2:a.strategy>=ot||a.level<2?4:0),At(a,3),a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;if(69===a.status){if(a.gzhead.extra){var _e4=a.pending,_i549=(65535&a.gzhead.extra.length)-a.gzindex;for(;a.pending+_i549>a.pending_buf_size;){var _n3=a.pending_buf_size-a.pending;if(a.pending_buf.set(a.gzhead.extra.subarray(a.gzindex,a.gzindex+_n3),a.pending),a.pending=a.pending_buf_size,a.gzhead.hcrc&&a.pending>_e4&&(t.adler=H(t.adler,a.pending_buf,a.pending-_e4,_e4)),a.gzindex+=_n3,xt(t),0!==a.pending)return a.last_flush=-1,tt;_e4=0,_i549-=_n3;}var _n2=new Uint8Array(a.gzhead.extra);a.pending_buf.set(_n2.subarray(a.gzindex,a.gzindex+_i549),a.pending),a.pending+=_i549,a.gzhead.hcrc&&a.pending>_e4&&(t.adler=H(t.adler,a.pending_buf,a.pending-_e4,_e4)),a.gzindex=0;}a.status=73;}if(73===a.status){if(a.gzhead.name){var _e5,_i550=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>_i550&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i550,_i550)),xt(t),0!==a.pending)return a.last_flush=-1,tt;_i550=0;}_e5=a.gzindex_i550&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i550,_i550)),a.gzindex=0;}a.status=91;}if(91===a.status){if(a.gzhead.comment){var _e6,_i551=a.pending;do{if(a.pending===a.pending_buf_size){if(a.gzhead.hcrc&&a.pending>_i551&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i551,_i551)),xt(t),0!==a.pending)return a.last_flush=-1,tt;_i551=0;}_e6=a.gzindex_i551&&(t.adler=H(t.adler,a.pending_buf,a.pending-_i551,_i551));}a.status=103;}if(103===a.status){if(a.gzhead.hcrc){if(a.pending+2>a.pending_buf_size&&(xt(t),0!==a.pending))return a.last_flush=-1,tt;At(a,255&t.adler),At(a,t.adler>>8&255),t.adler=0;}if(a.status=mt,xt(t),0!==a.pending)return a.last_flush=-1,tt;}if(0!==t.avail_in||0!==a.lookahead||e!==q&&a.status!==bt){var _i552=0===a.level?St(a,e):a.strategy===ot?function(t,e){var a;for(;;){if(0===t.lookahead&&(Ut(t),0===t.lookahead)){if(e===q)return 1;break;}if(t.match_length=0,a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,a&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;}(a,e):a.strategy===lt?function(t,e){var a,i,n,s;var r=t.window;for(;;){if(t.lookahead<=ct){if(Ut(t),t.lookahead<=ct&&e===q)return 1;if(0===t.lookahead)break;}if(t.match_length=0,t.lookahead>=3&&t.strstart>0&&(n=t.strstart-1,i=r[n],i===r[++n]&&i===r[++n]&&i===r[++n])){s=t.strstart+ct;do{}while(i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&i===r[++n]&&nt.lookahead&&(t.match_length=t.lookahead);}if(t.match_length>=3?(a=X(t,1,t.match_length-3),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(a=X(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),a&&(zt(t,!1),0===t.strm.avail_out))return 1;}return t.insert=0,e===V?(zt(t,!0),0===t.strm.avail_out?3:4):t.sym_next&&(zt(t,!1),0===t.strm.avail_out)?1:2;}(a,e):It[a.level].func(a,e);if(3!==_i552&&4!==_i552||(a.status=bt),1===_i552||3===_i552)return 0===t.avail_out&&(a.last_flush=-1),tt;if(2===_i552&&(e===J?W(a):e!==$&&(Y(a,0,0,!1),e===Q&&(kt(a.head),0===a.lookahead&&(a.strstart=0,a.block_start=0,a.insert=0))),xt(t),0===t.avail_out))return a.last_flush=-1,tt;}return e!==V?tt:a.wrap<=0?et:(2===a.wrap?(At(a,255&t.adler),At(a,t.adler>>8&255),At(a,t.adler>>16&255),At(a,t.adler>>24&255),At(a,255&t.total_in),At(a,t.total_in>>8&255),At(a,t.total_in>>16&255),At(a,t.total_in>>24&255)):(Et(a,t.adler>>>16),Et(a,65535&t.adler)),xt(t),a.wrap>0&&(a.wrap=-a.wrap),0!==a.pending?tt:et);},deflateEnd:function deflateEnd(t){if(Lt(t))return at;var e=t.state.status;return t.state=null,e===mt?gt(t,it):tt;},deflateSetDictionary:function deflateSetDictionary(t,e){var a=e.length;if(Lt(t))return at;var i=t.state,n=i.wrap;if(2===n||1===n&&i.status!==wt||i.lookahead)return at;if(1===n&&(t.adler=C(t.adler,e,a,0)),i.wrap=0,a>=i.w_size){0===n&&(kt(i.head),i.strstart=0,i.block_start=0,i.insert=0);var _t2=new Uint8Array(i.w_size);_t2.set(e.subarray(a-i.w_size,a),0),e=_t2,a=i.w_size;}var s=t.avail_in,r=t.next_in,o=t.input;for(t.avail_in=a,t.next_in=0,t.input=e,Ut(i);i.lookahead>=3;){var _t3=i.strstart,_e7=i.lookahead-2;do{i.ins_h=yt(i,i.ins_h,i.window[_t3+3-1]),i.prev[_t3&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=_t3,_t3++;}while(--_e7);i.strstart=_t3,i.lookahead=2,Ut(i);}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,t.next_in=r,t.input=o,t.avail_in=s,i.wrap=n,tt;},deflateInfo:"pako deflate (from Nodeca project)"};var Ht=function Ht(t,e){return Object.prototype.hasOwnProperty.call(t,e);};var jt=function jt(t){var e=Array.prototype.slice.call(arguments,1);for(;e.length;){var _a7=e.shift();if(_a7){if("object"!=_typeof(_a7))throw new TypeError(_a7+"must be non-object");for(var _e8 in _a7){Ht(_a7,_e8)&&(t[_e8]=_a7[_e8]);}}}return t;},Kt=function Kt(t){var e=0;for(var _a8=0,_i553=t.length;_a8<_i553;_a8++){e+=t[_a8].length;}var a=new Uint8Array(e);for(var _e9=0,_i554=0,_n4=t.length;_e9<_n4;_e9++){var _n5=t[_e9];a.set(_n5,_i554),_i554+=_n5.length;}return a;};var Pt=!0;try{String.fromCharCode.apply(null,new Uint8Array(1));}catch(t){Pt=!1;}var Yt=new Uint8Array(256);for(var _t4=0;_t4<256;_t4++){Yt[_t4]=_t4>=252?6:_t4>=248?5:_t4>=240?4:_t4>=224?3:_t4>=192?2:1;}Yt[254]=Yt[254]=1;var Gt=function Gt(t){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return new TextEncoder().encode(t);var e,a,i,n,s,r=t.length,o=0;for(n=0;n>>6,e[s++]=128|63&a):a<65536?(e[s++]=224|a>>>12,e[s++]=128|a>>>6&63,e[s++]=128|63&a):(e[s++]=240|a>>>18,e[s++]=128|a>>>12&63,e[s++]=128|a>>>6&63,e[s++]=128|63&a);}return e;},Xt=function Xt(t,e){var a=e||t.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return new TextDecoder().decode(t.subarray(0,e));var i,n;var s=new Array(2*a);for(n=0,i=0;i4)s[n++]=65533,i+=_r6-1;else{for(_e10&=2===_r6?31:3===_r6?15:7;_r6>1&&i1?s[n++]=65533:_e10<65536?s[n++]=_e10:(_e10-=65536,s[n++]=55296|_e10>>10&1023,s[n++]=56320|1023&_e10);}}return function(t,e){if(e<65534&&t.subarray&&Pt)return String.fromCharCode.apply(null,t.length===e?t:t.subarray(0,e));var a="";for(var _i555=0;_i555t.length&&(e=t.length);var a=e-1;for(;a>=0&&128==(192&t[a]);){a--;}return a<0||0===a?e:a+Yt[t[a]]>e?a:e;};var qt=function qt(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;};var Jt=Object.prototype.toString,Qt=K.Z_NO_FLUSH,Vt=K.Z_SYNC_FLUSH,$t=K.Z_FULL_FLUSH,te=K.Z_FINISH,ee=K.Z_OK,ae=K.Z_STREAM_END,ie=K.Z_DEFAULT_COMPRESSION,ne=K.Z_DEFAULT_STRATEGY,se=K.Z_DEFLATED;function re(t){this.options=jt({level:ie,method:se,chunkSize:16384,windowBits:15,memLevel:8,strategy:ne},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt(),this.strm.avail_out=0;var a=Mt.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(a!==ee)throw new Error(j[a]);if(e.header&&Mt.deflateSetHeader(this.strm,e.header),e.dictionary){var _t5;if(_t5="string"==typeof e.dictionary?Gt(e.dictionary):"[object ArrayBuffer]"===Jt.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,a=Mt.deflateSetDictionary(this.strm,_t5),a!==ee)throw new Error(j[a]);this._dict_set=!0;}}function oe(t,e){var a=new re(e);if(a.push(t,!0),a.err)throw a.msg||j[a.err];return a.result;}re.prototype.push=function(t,e){var a=this.strm,i=this.options.chunkSize;var n,s;if(this.ended)return!1;for(s=e===~~e?e:!0===e?te:Qt,"string"==typeof t?a.input=Gt(t):"[object ArrayBuffer]"===Jt.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){if(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),(s===Vt||s===$t)&&a.avail_out<=6)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else{if(n=Mt.deflate(a,s),n===ae)return a.next_out>0&&this.onData(a.output.subarray(0,a.next_out)),n=Mt.deflateEnd(this.strm),this.onEnd(n),this.ended=!0,n===ee;if(0!==a.avail_out){if(s>0&&a.next_out>0)this.onData(a.output.subarray(0,a.next_out)),a.avail_out=0;else if(0===a.avail_in)break;}else this.onData(a.output);}}return!0;},re.prototype.onData=function(t){this.chunks.push(t);},re.prototype.onEnd=function(t){t===ee&&(this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg;};var le={Deflate:re,deflate:oe,deflateRaw:function deflateRaw(t,e){return(e=e||{}).raw=!0,oe(t,e);},gzip:function gzip(t,e){return(e=e||{}).gzip=!0,oe(t,e);},constants:K};var he=16209;var de=function de(t,e){var a,i,n,s,r,o,l,h,d,_,f,c,u,w,m,b,g,p,k,v,y,x,z,A;var E=t.state;a=t.next_in,z=t.input,i=a+(t.avail_in-5),n=t.next_out,A=t.output,s=n-(e-t.avail_out),r=n+(t.avail_out-257),o=E.dmax,l=E.wsize,h=E.whave,d=E.wnext,_=E.window,f=E.hold,c=E.bits,u=E.lencode,w=E.distcode,m=(1<>>24,f>>>=p,c-=p,p=g>>>16&255,0===p)A[n++]=65535&g;else{if(!(16&p)){if(0==(64&p)){g=u[(65535&g)+(f&(1<>>=p,c-=p),c<15&&(f+=z[a++]<>>24,f>>>=p,c-=p,p=g>>>16&255,!(16&p)){if(0==(64&p)){g=w[(65535&g)+(f&(1<o){t.msg="invalid distance too far back",E.mode=he;break t;}if(f>>>=p,c-=p,p=n-s,v>p){if(p=v-p,p>h&&E.sane){t.msg="invalid distance too far back",E.mode=he;break t;}if(y=0,x=_,0===d){if(y+=l-p,p2;){A[n++]=x[y++],A[n++]=x[y++],A[n++]=x[y++],k-=3;}k&&(A[n++]=x[y++],k>1&&(A[n++]=x[y++]));}else{y=n-v;do{A[n++]=A[y++],A[n++]=A[y++],A[n++]=A[y++],k-=3;}while(k>2);k&&(A[n++]=A[y++],k>1&&(A[n++]=A[y++]));}break;}}break;}}while(a>3,a-=k,c-=k<<3,f&=(1<=1&&0===E[g];g--){;}if(p>g&&(p=g),0===g)return n[s++]=20971520,n[s++]=20971520,o.bits=1,0;for(b=1;b0&&(0===t||1!==g))return-1;for(R[1]=0,w=1;w<_e;w++){R[w+1]=R[w]+E[w];}for(m=0;m852||2===t&&x>592)return 1;for(;;){Z=w-v,r[m]+1=u?(U=D[r[m]-u],S=A[r[m]-u]):(U=96,S=0),h=1<>v)+d]=Z<<24|U<<16|S|0;}while(0!==d);for(h=1<>=1;}if(0!==h?(z&=h-1,z+=h):z=0,m++,0==--E[w]){if(w===g)break;w=e[a+r[m]];}if(w>p&&(z&f)!==_){for(0===v&&(v=p),c+=b,k=w-v,y=1<852||2===t&&x>592)return 1;_=z&f,n[_]=p<<24|k<<16|c-s|0;}}return 0!==z&&(n[c+z]=w-v<<24|64<<16|0),o.bits=p,0;};var be=K.Z_FINISH,ge=K.Z_BLOCK,pe=K.Z_TREES,ke=K.Z_OK,ve=K.Z_STREAM_END,ye=K.Z_NEED_DICT,xe=K.Z_STREAM_ERROR,ze=K.Z_DATA_ERROR,Ae=K.Z_MEM_ERROR,Ee=K.Z_BUF_ERROR,Re=K.Z_DEFLATED,Ze=16180,Ue=16190,Se=16191,De=16192,Te=16194,Oe=16199,Ie=16200,Fe=16206,Le=16209,Ne=function Ne(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24);};function Be(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}var Ce=function Ce(t){if(!t)return 1;var e=t.state;return!e||e.strm!==t||e.mode16211?1:0;},Me=function Me(t){if(Ce(t))return xe;var e=t.state;return t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=Ze,e.last=0,e.havedict=0,e.flags=-1,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Int32Array(852),e.distcode=e.distdyn=new Int32Array(592),e.sane=1,e.back=-1,ke;},He=function He(t){if(Ce(t))return xe;var e=t.state;return e.wsize=0,e.whave=0,e.wnext=0,Me(t);},je=function je(t,e){var a;if(Ce(t))return xe;var i=t.state;return e<0?(a=0,e=-e):(a=5+(e>>4),e<48&&(e&=15)),e&&(e<8||e>15)?xe:(null!==i.window&&i.wbits!==e&&(i.window=null),i.wrap=a,i.wbits=e,He(t));},Ke=function Ke(t,e){if(!t)return xe;var a=new Be();t.state=a,a.strm=t,a.window=null,a.mode=Ze;var i=je(t,e);return i!==ke&&(t.state=null),i;};var Pe,Ye,Ge=!0;var Xe=function Xe(t){if(Ge){Pe=new Int32Array(512),Ye=new Int32Array(32);var _e11=0;for(;_e11<144;){t.lens[_e11++]=8;}for(;_e11<256;){t.lens[_e11++]=9;}for(;_e11<280;){t.lens[_e11++]=7;}for(;_e11<288;){t.lens[_e11++]=8;}for(me(1,t.lens,0,288,Pe,0,t.work,{bits:9}),_e11=0;_e11<32;){t.lens[_e11++]=5;}me(2,t.lens,0,32,Ye,0,t.work,{bits:5}),Ge=!1;}t.lencode=Pe,t.lenbits=9,t.distcode=Ye,t.distbits=5;},We=function We(t,e,a,i){var n;var s=t.state;return null===s.window&&(s.wsize=1<=s.wsize?(s.window.set(e.subarray(a-s.wsize,a),0),s.wnext=0,s.whave=s.wsize):(n=s.wsize-s.wnext,n>i&&(n=i),s.window.set(e.subarray(a-i,a-i+n),s.wnext),(i-=n)?(s.window.set(e.subarray(a-i,a),0),s.wnext=i,s.whave=s.wsize):(s.wnext+=n,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,a.check=H(a.check,A,2,0),h=0,d=0,a.mode=16181;break;}if(a.head&&(a.head.done=!1),!(1&a.wrap)||(((255&h)<<8)+(h>>8))%31){t.msg="incorrect header check",a.mode=Le;break;}if((15&h)!==Re){t.msg="unknown compression method",a.mode=Le;break;}if(h>>>=4,d-=4,y=8+(15&h),0===a.wbits&&(a.wbits=y),y>15||y>a.wbits){t.msg="invalid window size",a.mode=Le;break;}a.dmax=1<>8&1),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16182;case 16182:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>8&255,A[2]=h>>>16&255,A[3]=h>>>24&255,a.check=H(a.check,A,4,0)),h=0,d=0,a.mode=16183;case 16183:for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>8),512&a.flags&&4&a.wrap&&(A[0]=255&h,A[1]=h>>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0,a.mode=16184;case 16184:if(1024&a.flags){for(;d<16;){if(0===o)break t;o--,h+=i[s++]<>>8&255,a.check=H(a.check,A,2,0)),h=0,d=0;}else a.head&&(a.head.extra=null);a.mode=16185;case 16185:if(1024&a.flags&&(c=a.length,c>o&&(c=o),c&&(a.head&&(y=a.head.extra_len-a.length,a.head.extra||(a.head.extra=new Uint8Array(a.head.extra_len)),a.head.extra.set(i.subarray(s,s+c),y)),512&a.flags&&4&a.wrap&&(a.check=H(a.check,i,c,s)),o-=c,s+=c,a.length-=c),a.length))break t;a.length=0,a.mode=16186;case 16186:if(2048&a.flags){if(0===o)break t;c=0;do{y=i[s+c++],a.head&&y&&a.length<65536&&(a.head.name+=String.fromCharCode(y));}while(y&&c>9&1,a.head.done=!0),t.adler=a.check=0,a.mode=Se;break;case 16189:for(;d<32;){if(0===o)break t;o--,h+=i[s++]<>>=7&d,d-=7&d,a.mode=Fe;break;}for(;d<3;){if(0===o)break t;o--,h+=i[s++]<>>=1,d-=1,3&h){case 0:a.mode=16193;break;case 1:if(Xe(a),a.mode=Oe,e===pe){h>>>=2,d-=2;break t;}break;case 2:a.mode=16196;break;case 3:t.msg="invalid block type",a.mode=Le;}h>>>=2,d-=2;break;case 16193:for(h>>>=7&d,d-=7&d;d<32;){if(0===o)break t;o--,h+=i[s++]<>>16^65535)){t.msg="invalid stored block lengths",a.mode=Le;break;}if(a.length=65535&h,h=0,d=0,a.mode=Te,e===pe)break t;case Te:a.mode=16195;case 16195:if(c=a.length,c){if(c>o&&(c=o),c>l&&(c=l),0===c)break t;n.set(i.subarray(s,s+c),r),o-=c,s+=c,l-=c,r+=c,a.length-=c;break;}a.mode=Se;break;case 16196:for(;d<14;){if(0===o)break t;o--,h+=i[s++]<>>=5,d-=5,a.ndist=1+(31&h),h>>>=5,d-=5,a.ncode=4+(15&h),h>>>=4,d-=4,a.nlen>286||a.ndist>30){t.msg="too many length or distance symbols",a.mode=Le;break;}a.have=0,a.mode=16197;case 16197:for(;a.have>>=3,d-=3;}for(;a.have<19;){a.lens[Z[a.have++]]=0;}if(a.lencode=a.lendyn,a.lenbits=7,E={bits:a.lenbits},x=me(0,a.lens,0,19,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid code lengths set",a.mode=Le;break;}a.have=0,a.mode=16198;case 16198:for(;a.have>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=m,d-=m,a.lens[a.have++]=g;else{if(16===g){for(R=m+2;d>>=m,d-=m,0===a.have){t.msg="invalid bit length repeat",a.mode=Le;break;}y=a.lens[a.have-1],c=3+(3&h),h>>>=2,d-=2;}else if(17===g){for(R=m+3;d>>=m,d-=m,y=0,c=3+(7&h),h>>>=3,d-=3;}else{for(R=m+7;d>>=m,d-=m,y=0,c=11+(127&h),h>>>=7,d-=7;}if(a.have+c>a.nlen+a.ndist){t.msg="invalid bit length repeat",a.mode=Le;break;}for(;c--;){a.lens[a.have++]=y;}}}if(a.mode===Le)break;if(0===a.lens[256]){t.msg="invalid code -- missing end-of-block",a.mode=Le;break;}if(a.lenbits=9,E={bits:a.lenbits},x=me(1,a.lens,0,a.nlen,a.lencode,0,a.work,E),a.lenbits=E.bits,x){t.msg="invalid literal/lengths set",a.mode=Le;break;}if(a.distbits=6,a.distcode=a.distdyn,E={bits:a.distbits},x=me(2,a.lens,a.nlen,a.ndist,a.distcode,0,a.work,E),a.distbits=E.bits,x){t.msg="invalid distances set",a.mode=Le;break;}if(a.mode=Oe,e===pe)break t;case Oe:a.mode=Ie;case Ie:if(o>=6&&l>=258){t.next_out=r,t.avail_out=l,t.next_in=s,t.avail_in=o,a.hold=h,a.bits=d,de(t,f),r=t.next_out,n=t.output,l=t.avail_out,s=t.next_in,i=t.input,o=t.avail_in,h=a.hold,d=a.bits,a.mode===Se&&(a.back=-1);break;}for(a.back=0;z=a.lencode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p;}if(h>>>=m,d-=m,a.back+=m,a.length=g,0===b){a.mode=16205;break;}if(32&b){a.back=-1,a.mode=Se;break;}if(64&b){t.msg="invalid literal/length code",a.mode=Le;break;}a.extra=15&b,a.mode=16201;case 16201:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra;}a.was=a.length,a.mode=16202;case 16202:for(;z=a.distcode[h&(1<>>24,b=z>>>16&255,g=65535&z,!(m<=d);){if(0===o)break t;o--,h+=i[s++]<>p)],m=z>>>24,b=z>>>16&255,g=65535&z,!(p+m<=d);){if(0===o)break t;o--,h+=i[s++]<>>=p,d-=p,a.back+=p;}if(h>>>=m,d-=m,a.back+=m,64&b){t.msg="invalid distance code",a.mode=Le;break;}a.offset=g,a.extra=15&b,a.mode=16203;case 16203:if(a.extra){for(R=a.extra;d>>=a.extra,d-=a.extra,a.back+=a.extra;}if(a.offset>a.dmax){t.msg="invalid distance too far back",a.mode=Le;break;}a.mode=16204;case 16204:if(0===l)break t;if(c=f-l,a.offset>c){if(c=a.offset-c,c>a.whave&&a.sane){t.msg="invalid distance too far back",a.mode=Le;break;}c>a.wnext?(c-=a.wnext,u=a.wsize-c):u=a.wnext-c,c>a.length&&(c=a.length),w=a.window;}else w=n,u=r-a.offset,c=a.length;c>l&&(c=l),l-=c,a.length-=c;do{n[r++]=w[u++];}while(--c);0===a.length&&(a.mode=Ie);break;case 16205:if(0===l)break t;n[r++]=a.length,l--,a.mode=Ie;break;case Fe:if(a.wrap){for(;d<32;){if(0===o)break t;o--,h|=i[s++]<=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(e.windowBits>=0&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&0==(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new qt(),this.strm.avail_out=0;var a=qe.inflateInit2(this.strm,e.windowBits);if(a!==ta)throw new Error(j[a]);if(this.header=new Je(),qe.inflateGetHeader(this.strm,this.header),e.dictionary&&("string"==typeof e.dictionary?e.dictionary=Gt(e.dictionary):"[object ArrayBuffer]"===Qe.call(e.dictionary)&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(a=qe.inflateSetDictionary(this.strm,e.dictionary),a!==ta)))throw new Error(j[a]);}function oa(t,e){var a=new ra(e);if(a.push(t),a.err)throw a.msg||j[a.err];return a.result;}ra.prototype.push=function(t,e){var a=this.strm,i=this.options.chunkSize,n=this.options.dictionary;var s,r,o;if(this.ended)return!1;for(r=e===~~e?e:!0===e?$e:Ve,"[object ArrayBuffer]"===Qe.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;;){for(0===a.avail_out&&(a.output=new Uint8Array(i),a.next_out=0,a.avail_out=i),s=qe.inflate(a,r),s===aa&&n&&(s=qe.inflateSetDictionary(a,n),s===ta?s=qe.inflate(a,r):s===na&&(s=aa));a.avail_in>0&&s===ea&&a.state.wrap>0&&0!==t[a.next_in];){qe.inflateReset(a),s=qe.inflate(a,r);}switch(s){case ia:case na:case aa:case sa:return this.onEnd(s),this.ended=!0,!1;}if(o=a.avail_out,a.next_out&&(0===a.avail_out||s===ea))if("string"===this.options.to){var _t6=Wt(a.output,a.next_out),_e12=a.next_out-_t6,_n6=Xt(a.output,_t6);a.next_out=_e12,a.avail_out=i-_e12,_e12&&a.output.set(a.output.subarray(_t6,_t6+_e12),0),this.onData(_n6);}else this.onData(a.output.length===a.next_out?a.output:a.output.subarray(0,a.next_out));if(s!==ta||0!==o){if(s===ea)return s=qe.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,!0;if(0===a.avail_in)break;}}return!0;},ra.prototype.onData=function(t){this.chunks.push(t);},ra.prototype.onEnd=function(t){t===ta&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=Kt(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg;};var la={Inflate:ra,inflate:oa,inflateRaw:function inflateRaw(t,e){return(e=e||{}).raw=!0,oa(t,e);},ungzip:oa,constants:K};var ha=le.Deflate,da=le.deflate,_a=le.deflateRaw,fa=le.gzip,ca=la.Inflate,ua=la.inflate,wa=la.inflateRaw,ma=la.ungzip;var ba=ha,ga=da,pa=_a,ka=fa,va=ca,ya=ua,xa=wa,za=ma,Aa=K,Ea={Deflate:ba,deflate:ga,deflateRaw:pa,gzip:ka,Inflate:va,inflate:ya,inflateRaw:xa,ungzip:za,constants:Aa};t.Deflate=ba,t.Inflate=va,t.constants=Aa,t["default"]=Ea,t.deflate=ga,t.deflateRaw=pa,t.gzip=ka,t.inflate=ya,t.inflateRaw=xa,t.ungzip=za,Object.defineProperty(t,"__esModule",{value:!0});});var p=/*#__PURE__*/Object.freeze({__proto__:null});/* Parser for .XKT Format V1 @@ -27381,7 +27387,7 @@ var isBase64=!!dataUriRegexResult[2];var data=dataUriRegexResult[3];data=window. DEPRECATED */var pako$9=window.pako||p;if(!pako$9.inflate){// See https://github.com/nodeca/pako/issues/97 -pako$9=pako$9["default"];}var decompressColor$9=function(){var color2=new Float32Array(3);return function(color){color2[0]=color[0]/255.0;color2[1]=color[1]/255.0;color2[2]=color[2]/255.0;return color2;};}();function extract$9(elements){return{positions:elements[0],normals:elements[1],indices:elements[2],edgeIndices:elements[3],meshPositions:elements[4],meshIndices:elements[5],meshEdgesIndices:elements[6],meshColors:elements[7],entityIDs:elements[8],entityMeshes:elements[9],entityIsObjects:elements[10],positionsDecodeMatrix:elements[11]};}function inflate$9(deflatedData){return{positions:new Uint16Array(pako$9.inflate(deflatedData.positions).buffer),normals:new Int8Array(pako$9.inflate(deflatedData.normals).buffer),indices:new Uint32Array(pako$9.inflate(deflatedData.indices).buffer),edgeIndices:new Uint32Array(pako$9.inflate(deflatedData.edgeIndices).buffer),meshPositions:new Uint32Array(pako$9.inflate(deflatedData.meshPositions).buffer),meshIndices:new Uint32Array(pako$9.inflate(deflatedData.meshIndices).buffer),meshEdgesIndices:new Uint32Array(pako$9.inflate(deflatedData.meshEdgesIndices).buffer),meshColors:new Uint8Array(pako$9.inflate(deflatedData.meshColors).buffer),entityIDs:pako$9.inflate(deflatedData.entityIDs,{to:'string'}),entityMeshes:new Uint32Array(pako$9.inflate(deflatedData.entityMeshes).buffer),entityIsObjects:new Uint8Array(pako$9.inflate(deflatedData.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(pako$9.inflate(deflatedData.positionsDecodeMatrix).buffer)};}function load$9(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx){manifestCtx.getNextId();sceneModel.positionsCompression="precompressed";sceneModel.normalsCompression="precompressed";var positions=inflatedData.positions;var normals=inflatedData.normals;var indices=inflatedData.indices;var edgeIndices=inflatedData.edgeIndices;var meshPositions=inflatedData.meshPositions;var meshIndices=inflatedData.meshIndices;var meshEdgesIndices=inflatedData.meshEdgesIndices;var meshColors=inflatedData.meshColors;var entityIDs=JSON.parse(inflatedData.entityIDs);var entityMeshes=inflatedData.entityMeshes;var entityIsObjects=inflatedData.entityIsObjects;var numMeshes=meshPositions.length;var numEntities=entityMeshes.length;for(var _i554=0;_i5541;var atLastGeometry=_geometryIndex2===numGeometries-1;var meshColor=decompressColor$2(eachMeshMaterial.subarray(_meshIndex2*6,_meshIndex2*6+3));var meshOpacity=eachMeshMaterial[_meshIndex2*6+3]/255.0;var meshMetallic=eachMeshMaterial[_meshIndex2*6+4]/255.0;var meshRoughness=eachMeshMaterial[_meshIndex2*6+5]/255.0;var meshId=manifestCtx.getNextId();if(isReusedGeometry){// Create mesh for multi-use geometry - create (or reuse) geometry, create mesh using that geometry var meshMatrixIndex=eachMeshMatricesPortion[_meshIndex2];var meshMatrix=matrices.slice(meshMatrixIndex,meshMatrixIndex+16);var geometryId="".concat(modelPartId,"-geometry.").concat(tileIndex,".").concat(_geometryIndex2);// These IDs are local to the SceneModel -var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex2];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryColors=convertColorsRGBToRGBA(colors.subarray(eachGeometryColorsPortion[_geometryIndex2],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex2+1]));geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i559=0,len=geometryPositions.length;_i5590&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);_geometryValid=_geometryPositions2.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryColors=convertColorsRGBToRGBA(colors.subarray(eachGeometryColorsPortion[_geometryIndex2],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex2+1]));_geometryValid=_geometryPositions2.length>0;break;case 3:primitiveName="lines";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);_geometryValid=_geometryPositions2.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions2,normalsCompressed:geometryNormals,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}/** @private */var ParserV8={version:8,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract$2(elements);var inflatedData=inflate$2(deflatedData);load$2(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};/* +var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex2];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryColors=convertColorsRGBToRGBA(colors.subarray(eachGeometryColorsPortion[_geometryIndex2],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex2+1]));geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i561=0,len=geometryPositions.length;_i5610&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex2],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex2+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex2],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex2+1]);_geometryValid=_geometryPositions2.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryColors=convertColorsRGBToRGBA(colors.subarray(eachGeometryColorsPortion[_geometryIndex2],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex2+1]));_geometryValid=_geometryPositions2.length>0;break;case 3:primitiveName="lines";_geometryPositions2=positions.subarray(eachGeometryPositionsPortion[_geometryIndex2],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex2+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex2],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex2+1]);_geometryValid=_geometryPositions2.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions2,normalsCompressed:geometryNormals,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}/** @private */var ParserV8={version:8,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract$2(elements);var inflatedData=inflate$2(deflatedData);load$2(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};/* Parser for .XKT Format V9 @@ -27515,7 +27521,7 @@ if(options.excludeTypesMap&&metaObject.type&&options.excludeTypesMap[metaObject. var props=options.objectDefaults?options.objectDefaults[metaObject.type]||options.objectDefaults["DEFAULT"]:null;if(props){if(props.visible===false){entityDefaults.visible=false;}if(props.pickable===false){entityDefaults.pickable=false;}if(props.colorize){meshDefaults.color=props.colorize;}if(props.opacity!==undefined&&props.opacity!==null){meshDefaults.opacity=props.opacity;}if(props.metallic!==undefined&&props.metallic!==null){meshDefaults.metallic=props.metallic;}if(props.roughness!==undefined&&props.roughness!==null){meshDefaults.roughness=props.roughness;}}}else{if(options.excludeUnclassifiedObjects){continue;}}// Iterate each entity's meshes for(var _meshIndex3=firstMeshIndex;_meshIndex3<=lastMeshIndex;_meshIndex3++){var _geometryIndex3=eachMeshGeometriesPortion[_meshIndex3];var geometryReuseCount=geometryReuseCounts[_geometryIndex3];var isReusedGeometry=geometryReuseCount>1;var atLastGeometry=_geometryIndex3===numGeometries-1;var meshColor=decompressColor$1(eachMeshMaterial.subarray(_meshIndex3*6,_meshIndex3*6+3));var meshOpacity=eachMeshMaterial[_meshIndex3*6+3]/255.0;var meshMetallic=eachMeshMaterial[_meshIndex3*6+4]/255.0;var meshRoughness=eachMeshMaterial[_meshIndex3*6+5]/255.0;var meshId=manifestCtx.getNextId();if(isReusedGeometry){// Create mesh for multi-use geometry - create (or reuse) geometry, create mesh using that geometry var meshMatrixIndex=eachMeshMatricesPortion[_meshIndex3];var meshMatrix=matrices.slice(meshMatrixIndex,meshMatrixIndex+16);var geometryId="".concat(modelPartId,"-geometry.").concat(tileIndex,".").concat(_geometryIndex3);// These IDs are local to the SceneModel -var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex3];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex3],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);geometryArrays.transformedAndRecompressedPositions=new Uint16Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i561=0,len=geometryPositions.length;_i5610&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex3],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0;break;case 3:primitiveName="lines";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid2){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions3,normalsCompressed:geometryNormals,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}/** @private */var ParserV9={version:9,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract$1(elements);var inflatedData=inflate$1(deflatedData);load$1(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};/* +var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex3];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex3],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);geometryArrays.transformedAndRecompressedPositions=new Uint16Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i563=0,len=geometryPositions.length;_i5630&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex3],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex3+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex3],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex3],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0;break;case 3:primitiveName="lines";_geometryPositions3=positions.subarray(eachGeometryPositionsPortion[_geometryIndex3],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex3+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex3],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex3+1]);_geometryValid2=_geometryPositions3.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid2){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions3,normalsCompressed:geometryNormals,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}/** @private */var ParserV9={version:9,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract$1(elements);var inflatedData=inflate$1(deflatedData);load$1(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};/* Parser for .XKT Format V10 */var pako=window.pako||p;if(!pako.inflate){// See https://github.com/nodeca/pako/issues/97 pako=pako["default"];}var tempVec4a=math.vec4();var tempVec4b=math.vec4();var NUM_TEXTURE_ATTRIBUTES=9;function extract(elements){var i=0;return{metadata:elements[i++],textureData:elements[i++],eachTextureDataPortion:elements[i++],eachTextureAttributes:elements[i++],positions:elements[i++],normals:elements[i++],colors:elements[i++],uvs:elements[i++],indices:elements[i++],edgeIndices:elements[i++],eachTextureSetTextures:elements[i++],matrices:elements[i++],reusedGeometriesDecodeMatrix:elements[i++],eachGeometryPrimitiveType:elements[i++],eachGeometryPositionsPortion:elements[i++],eachGeometryNormalsPortion:elements[i++],eachGeometryColorsPortion:elements[i++],eachGeometryUVsPortion:elements[i++],eachGeometryIndicesPortion:elements[i++],eachGeometryEdgeIndicesPortion:elements[i++],eachMeshGeometriesPortion:elements[i++],eachMeshMatricesPortion:elements[i++],eachMeshTextureSet:elements[i++],eachMeshMaterialAttributes:elements[i++],eachEntityId:elements[i++],eachEntityMeshesPortion:elements[i++],eachTileAABB:elements[i++],eachTileEntitiesPortion:elements[i++]};}function inflate(deflatedData){function inflate(array,options){return array.length===0?[]:pako.inflate(array,options).buffer;}return{metadata:JSON.parse(pako.inflate(deflatedData.metadata,{to:'string'})),textureData:new Uint8Array(inflate(deflatedData.textureData)),// <<----------------------------- ??? ZIPPing to blame? @@ -27536,8 +27542,8 @@ if(options.excludeTypesMap&&metaObject.type&&options.excludeTypesMap[metaObject. var props=options.objectDefaults?options.objectDefaults[metaObject.type]||options.objectDefaults["DEFAULT"]:null;if(props){if(props.visible===false){entityDefaults.visible=false;}if(props.pickable===false){entityDefaults.pickable=false;}if(props.colorize){meshDefaults.color=props.colorize;}if(props.opacity!==undefined&&props.opacity!==null){meshDefaults.opacity=props.opacity;}if(props.metallic!==undefined&&props.metallic!==null){meshDefaults.metallic=props.metallic;}if(props.roughness!==undefined&&props.roughness!==null){meshDefaults.roughness=props.roughness;}}}else{if(options.excludeUnclassifiedObjects){continue;}}// Iterate each entity's meshes for(var _meshIndex4=firstMeshIndex;_meshIndex4<=lastMeshIndex;_meshIndex4++){var _geometryIndex4=eachMeshGeometriesPortion[_meshIndex4];var geometryReuseCount=geometryReuseCounts[_geometryIndex4];var isReusedGeometry=geometryReuseCount>1;var atLastGeometry=_geometryIndex4===numGeometries-1;var _textureSetIndex=eachMeshTextureSet[_meshIndex4];var _textureSetId=_textureSetIndex>=0?"".concat(modelPartId,"-textureSet-").concat(_textureSetIndex):null;var meshColor=decompressColor(eachMeshMaterialAttributes.subarray(_meshIndex4*6,_meshIndex4*6+3));var meshOpacity=eachMeshMaterialAttributes[_meshIndex4*6+3]/255.0;var meshMetallic=eachMeshMaterialAttributes[_meshIndex4*6+4]/255.0;var meshRoughness=eachMeshMaterialAttributes[_meshIndex4*6+5]/255.0;var meshId=manifestCtx.getNextId();if(isReusedGeometry){// Create mesh for multi-use geometry - create (or reuse) geometry, create mesh using that geometry var meshMatrixIndex=eachMeshMatricesPortion[_meshIndex4];var meshMatrix=matrices.slice(meshMatrixIndex,meshMatrixIndex+16);var geometryId="".concat(modelPartId,"-geometry.").concat(tileIndex,".").concat(_geometryIndex4);// These IDs are local to the SceneModel -var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex4];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryArrays.geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryArrays.geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex4],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 4:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=lineStripToLines(geometryArrays.geometryPositions,indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]));geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);geometryArrays.transformedAndRecompressedPositions=new Uint16Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i563=0,len=geometryPositions.length;_i5630&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex4],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0;break;case 3:primitiveName="lines";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;case 4:primitiveName="lines";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryIndices=lineStripToLines(_geometryPositions4,indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]));_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid3){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,textureSetId:_textureSetId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions4,normalsCompressed:geometryNormals,uv:geometryUVs&&geometryUVs.length>0?geometryUVs:null,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}function lineStripToLines(positions,indices){var linesIndices=[];if(indices.length>1){for(var _i565=0,len=indices.length-1;_i5651){for(var _i566=0,_len118=positions.length/3-1;_i566<_len118;_i566++){linesIndices.push(_i566);linesIndices.push(_i566+1);}}return linesIndices;}/** @private */var ParserV10={version:10,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract(elements);var inflatedData=inflate(deflatedData);load(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};var parsers={};parsers[ParserV1.version]=ParserV1;parsers[ParserV2.version]=ParserV2;parsers[ParserV3.version]=ParserV3;parsers[ParserV4.version]=ParserV4;parsers[ParserV5.version]=ParserV5;parsers[ParserV6.version]=ParserV6;parsers[ParserV7.version]=ParserV7;parsers[ParserV8.version]=ParserV8;parsers[ParserV9.version]=ParserV9;parsers[ParserV10.version]=ParserV10;/** +var geometryArrays=geometryArraysCache[geometryId];if(!geometryArrays){geometryArrays={batchThisMesh:!options.reuseGeometries};var primitiveType=eachGeometryPrimitiveType[_geometryIndex4];var geometryValid=false;switch(primitiveType){case 0:geometryArrays.primitiveName="solid";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryArrays.geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 1:geometryArrays.primitiveName="surface";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryArrays.geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryArrays.geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 2:geometryArrays.primitiveName="points";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex4],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0;break;case 3:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;case 4:geometryArrays.primitiveName="lines";geometryArrays.geometryPositions=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryArrays.geometryIndices=lineStripToLines(geometryArrays.geometryPositions,indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]));geometryValid=geometryArrays.geometryPositions.length>0&&geometryArrays.geometryIndices.length>0;break;default:continue;}if(!geometryValid){geometryArrays=null;}if(geometryArrays){if(geometryArrays.geometryPositions.length>1000);if(geometryArrays.batchThisMesh){geometryArrays.decompressedPositions=new Float32Array(geometryArrays.geometryPositions.length);geometryArrays.transformedAndRecompressedPositions=new Uint16Array(geometryArrays.geometryPositions.length);var geometryPositions=geometryArrays.geometryPositions;var decompressedPositions=geometryArrays.decompressedPositions;for(var _i565=0,len=geometryPositions.length;_i5650&&geometryIndices.length>0;break;case 1:primitiveName="surface";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryNormals=normals.subarray(eachGeometryNormalsPortion[_geometryIndex4],atLastGeometry?normals.length:eachGeometryNormalsPortion[_geometryIndex4+1]);geometryUVs=uvs.subarray(eachGeometryUVsPortion[_geometryIndex4],atLastGeometry?uvs.length:eachGeometryUVsPortion[_geometryIndex4+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);geometryEdgeIndices=edgeIndices.subarray(eachGeometryEdgeIndicesPortion[_geometryIndex4],atLastGeometry?edgeIndices.length:eachGeometryEdgeIndicesPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;case 2:primitiveName="points";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryColors=colors.subarray(eachGeometryColorsPortion[_geometryIndex4],atLastGeometry?colors.length:eachGeometryColorsPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0;break;case 3:primitiveName="lines";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryIndices=indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]);_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;case 4:primitiveName="lines";_geometryPositions4=positions.subarray(eachGeometryPositionsPortion[_geometryIndex4],atLastGeometry?positions.length:eachGeometryPositionsPortion[_geometryIndex4+1]);geometryIndices=lineStripToLines(_geometryPositions4,indices.subarray(eachGeometryIndicesPortion[_geometryIndex4],atLastGeometry?indices.length:eachGeometryIndicesPortion[_geometryIndex4+1]));_geometryValid3=_geometryPositions4.length>0&&geometryIndices.length>0;break;default:continue;}if(_geometryValid3){sceneModel.createMesh(utils.apply(meshDefaults,{id:meshId,textureSetId:_textureSetId,origin:tileCenter,primitive:primitiveName,positionsCompressed:_geometryPositions4,normalsCompressed:geometryNormals,uv:geometryUVs&&geometryUVs.length>0?geometryUVs:null,colorsCompressed:geometryColors,indices:geometryIndices,edgeIndices:geometryEdgeIndices,positionsDecodeMatrix:tileDecodeMatrix,color:meshColor,metallic:meshMetallic,roughness:meshRoughness,opacity:meshOpacity}));meshIds.push(meshId);}}}if(meshIds.length>0){sceneModel.createEntity(utils.apply(entityDefaults,{id:entityId,isObject:true,meshIds:meshIds}));}}}}function lineStripToLines(positions,indices){var linesIndices=[];if(indices.length>1){for(var _i567=0,len=indices.length-1;_i5671){for(var _i568=0,_len118=positions.length/3-1;_i568<_len118;_i568++){linesIndices.push(_i568);linesIndices.push(_i568+1);}}return linesIndices;}/** @private */var ParserV10={version:10,parse:function parse(viewer,options,elements,sceneModel,metaModel,manifestCtx){var deflatedData=extract(elements);var inflatedData=inflate(deflatedData);load(viewer,options,inflatedData,sceneModel,metaModel,manifestCtx);}};var parsers={};parsers[ParserV1.version]=ParserV1;parsers[ParserV2.version]=ParserV2;parsers[ParserV3.version]=ParserV3;parsers[ParserV4.version]=ParserV4;parsers[ParserV5.version]=ParserV5;parsers[ParserV6.version]=ParserV6;parsers[ParserV7.version]=ParserV7;parsers[ParserV8.version]=ParserV8;parsers[ParserV9.version]=ParserV9;parsers[ParserV10.version]=ParserV10;/** * {@link Viewer} plugin that loads models from xeokit's optimized *````.XKT````* format. * * @@ -28285,13 +28291,13 @@ var _primitiveType4=eachGeometryPrimitiveType[_geometryIndex4];var primitiveName * primitives. Only works while {@link DTX#enabled} is also ````true````. * @returns {Entity} Entity representing the model, which will have {@link Entity#isModel} set ````true```` and will be registered by {@link Entity#id} in {@link Scene#models}. */},{key:"load",value:function load(){var _this160=this;var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}if(!params.src&&!params.xkt&&!params.manifestSrc&&!params.manifest){this.error("load() param expected: src, xkt, manifestSrc or manifestData");return sceneModel;// Return new empty model -}var options={};var includeTypes=params.includeTypes||this._includeTypes;var excludeTypes=params.excludeTypes||this._excludeTypes;var objectDefaults=params.objectDefaults||this._objectDefaults;options.reuseGeometries=params.reuseGeometries!==null&¶ms.reuseGeometries!==undefined?params.reuseGeometries:this._reuseGeometries!==false;if(includeTypes){options.includeTypesMap={};for(var _i567=0,len=includeTypes.length;_i567=metaDataFiles.length){done();}else{_this160._dataSource.getMetaModel("".concat(baseDir).concat(metaDataFiles[i]),function(metaModelData){metaModel.loadData(metaModelData,{includeTypes:includeTypes,excludeTypes:excludeTypes,globalizeObjectIds:options.globalizeObjectIds});i++;_this160.scheduleTask(loadNext,100);},error);}};loadNext();};var loadXKTs_excludeTheirMetaModels=function loadXKTs_excludeTheirMetaModels(xktFiles,done,error){// Load XKTs, ignore metamodels in the XKT var i=0;var loadNext=function loadNext(){if(i>=xktFiles.length){done();}else{_this160._dataSource.getXKT("".concat(baseDir).concat(xktFiles[i]),function(arrayBuffer){_this160._parseModel(arrayBuffer,params,options,sceneModel,null/* Ignore metamodel in XKT */,manifestCtx);i++;_this160.scheduleTask(loadNext,100);},error);}};loadNext();};var loadXKTs_includeTheirMetaModels=function loadXKTs_includeTheirMetaModels(xktFiles,done,error){// Load XKTs, parse metamodels from the XKT -var i=0;var loadNext=function loadNext(){if(i>=xktFiles.length){done();}else{_this160._dataSource.getXKT("".concat(baseDir).concat(xktFiles[i]),function(arrayBuffer){_this160._parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx);i++;_this160.scheduleTask(loadNext,100);},error);}};loadNext();};if(params.manifest){var manifestData=params.manifest;var xktFiles=manifestData.xktFiles;if(!xktFiles||xktFiles.length===0){error("load(): Failed to load model manifest - manifest not valid");return;}var metaModelFiles=manifestData.metaModelFiles;if(metaModelFiles){loadJSONs(metaModelFiles,function(){loadXKTs_excludeTheirMetaModels(xktFiles,finish,error);},error);}else{loadXKTs_includeTheirMetaModels(xktFiles,finish,error);}}else{this._dataSource.getManifest(params.manifestSrc,function(manifestData){if(sceneModel.destroyed){return;}var xktFiles=manifestData.xktFiles;if(!xktFiles||xktFiles.length===0){error("load(): Failed to load model manifest - manifest not valid");return;}var metaModelFiles=manifestData.metaModelFiles;if(metaModelFiles){loadJSONs(metaModelFiles,function(){loadXKTs_excludeTheirMetaModels(xktFiles,finish,error);},error);}else{loadXKTs_includeTheirMetaModels(xktFiles,finish,error);}},error);}}}return sceneModel;}},{key:"_loadModel",value:function _loadModel(src,params,options,sceneModel,metaModel,manifestCtx,done,error){var _this161=this;this._dataSource.getXKT(params.src,function(arrayBuffer){_this161._parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx);done();},error);}},{key:"_parseModel",value:function _parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx){if(sceneModel.destroyed){return;}var dataView=new DataView(arrayBuffer);var dataArray=new Uint8Array(arrayBuffer);var xktVersion=dataView.getUint32(0,true);var parser=parsers[xktVersion];if(!parser){this.error("Unsupported .XKT file version: "+xktVersion+" - this XKTLoaderPlugin supports versions "+Object.keys(parsers));return;}this.log("Loading .xkt V"+xktVersion);var numElements=dataView.getUint32(4,true);var elements=[];var byteOffset=(numElements+2)*4;for(var _i569=0;_i569=xktFiles.length){done();}else{_this160._dataSource.getXKT("".concat(baseDir).concat(xktFiles[i]),function(arrayBuffer){_this160._parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx);i++;_this160.scheduleTask(loadNext,100);},error);}};loadNext();};if(params.manifest){var manifestData=params.manifest;var xktFiles=manifestData.xktFiles;if(!xktFiles||xktFiles.length===0){error("load(): Failed to load model manifest - manifest not valid");return;}var metaModelFiles=manifestData.metaModelFiles;if(metaModelFiles){loadJSONs(metaModelFiles,function(){loadXKTs_excludeTheirMetaModels(xktFiles,finish,error);},error);}else{loadXKTs_includeTheirMetaModels(xktFiles,finish,error);}}else{this._dataSource.getManifest(params.manifestSrc,function(manifestData){if(sceneModel.destroyed){return;}var xktFiles=manifestData.xktFiles;if(!xktFiles||xktFiles.length===0){error("load(): Failed to load model manifest - manifest not valid");return;}var metaModelFiles=manifestData.metaModelFiles;if(metaModelFiles){loadJSONs(metaModelFiles,function(){loadXKTs_excludeTheirMetaModels(xktFiles,finish,error);},error);}else{loadXKTs_includeTheirMetaModels(xktFiles,finish,error);}},error);}}}return sceneModel;}},{key:"_loadModel",value:function _loadModel(src,params,options,sceneModel,metaModel,manifestCtx,done,error){var _this161=this;this._dataSource.getXKT(params.src,function(arrayBuffer){_this161._parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx);done();},error);}},{key:"_parseModel",value:function _parseModel(arrayBuffer,params,options,sceneModel,metaModel,manifestCtx){if(sceneModel.destroyed){return;}var dataView=new DataView(arrayBuffer);var dataArray=new Uint8Array(arrayBuffer);var xktVersion=dataView.getUint32(0,true);var parser=parsers[xktVersion];if(!parser){this.error("Unsupported .XKT file version: "+xktVersion+" - this XKTLoaderPlugin supports versions "+Object.keys(parsers));return;}this.log("Loading .xkt V"+xktVersion);var numElements=dataView.getUint32(4,true);var elements=[];var byteOffset=(numElements+2)*4;for(var _i571=0;_i5710&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true}));if(!params.src&&!params.ifc){this.error("load() param expected: src or IFC");return sceneModel;// Return new empty model -}var options={autoNormals:true};if(params.loadMetadata!==false){var includeTypes=params.includeTypes||this._includeTypes;var excludeTypes=params.excludeTypes||this._excludeTypes;var objectDefaults=params.objectDefaults||this._objectDefaults;if(includeTypes){options.includeTypesMap={};for(var _i570=0,len=includeTypes.length;_i5700){var propertySetType="Default";var propertySetName=relatingPropertyDefinition.Name.value;var properties=[];for(var _i576=0,len=props.length;_i5760){var propertySetType="Default";var propertySetName=relatingPropertyDefinition.Name.value;var properties=[];for(var _i578=0,len=props.length;_i5780&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true}));if(!params.src&&!params.las){this.error("load() param expected: src or las");return sceneModel;// Return new empty model -}var options={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(params.src){this._loadModel(params.src,params,options,sceneModel);}else{var spinner=this.viewer.scene.canvas.spinner;spinner.processes++;this._parseModel(params.las,params,options,sceneModel).then(function(){spinner.processes--;},function(errMsg){spinner.processes--;_this168.error(errMsg);sceneModel.fire("error",errMsg);});}return sceneModel;}},{key:"_loadModel",value:function _loadModel(src,params,options,sceneModel){var _this169=this;var spinner=this.viewer.scene.canvas.spinner;spinner.processes++;this._dataSource.getLAS(params.src,function(arrayBuffer){_this169._parseModel(arrayBuffer,params,options,sceneModel).then(function(){spinner.processes--;},function(errMsg){spinner.processes--;_this169.error(errMsg);sceneModel.fire("error",errMsg);});},function(errMsg){spinner.processes--;_this169.error(errMsg);sceneModel.fire("error",errMsg);});}},{key:"_parseModel",value:function _parseModel(arrayBuffer,params,options,sceneModel){var _this170=this;function readPositions(attributesPosition){var positionsValue=attributesPosition.value;if(params.rotateX){if(positionsValue){for(var _i579=0,len=positionsValue.length;_i579=array.length){return[array];}var result=[];for(var _i583=0;_i583=array.length){return[array];}var result=[];for(var _i585=0;_i5850&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck(this,CityJSONDefaultDataSource);this.cacheBuster=cfg.cacheBuster!==false;}_createClass(CityJSONDefaultDataSource,[{key:"_cacheBusterURL",value:function _cacheBusterURL(url){if(!this.cacheBuster){return url;}var timestamp=new Date().getTime();if(url.indexOf('?')>-1){return url+'&_='+timestamp;}else{return url+'?_='+timestamp;}}/** * Gets the contents of the given CityJSON file. @@ -29702,16 +29708,16 @@ earcut.flatten=function(data){var dim=data[0][0].length,result={vertices:[],hole */},{key:"load",value:function load(){var params=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true,edges:true}));if(!params.src&&!params.cityJSON){this.error("load() param expected: src or cityJSON");return sceneModel;// Return new empty model }var options={};if(params.src){this._loadModel(params.src,params,options,sceneModel);}else{var spinner=this.viewer.scene.canvas.spinner;spinner.processes++;this._parseModel(params.cityJSON,params,options,sceneModel);spinner.processes--;}return sceneModel;}},{key:"_loadModel",value:function _loadModel(src,params,options,sceneModel){var _this172=this;var spinner=this.viewer.scene.canvas.spinner;spinner.processes++;this._dataSource.getCityJSON(params.src,function(data){_this172._parseModel(data,params,options,sceneModel);spinner.processes--;},function(errMsg){spinner.processes--;_this172.error(errMsg);sceneModel.fire("error",errMsg);});}},{key:"_parseModel",value:function _parseModel(data,params,options,sceneModel){if(sceneModel.destroyed){return;}var vertices=data.transform?this._transformVertices(data.vertices,data.transform,options.rotateX):data.vertices;var stats=params.stats||{};stats.sourceFormat=data.type||"CityJSON";stats.schemaVersion=data.version||"";stats.title="";stats.author="";stats.created="";stats.numMetaObjects=0;stats.numPropertySets=0;stats.numObjects=0;stats.numGeometries=0;stats.numTriangles=0;stats.numVertices=0;var loadMetadata=params.loadMetadata!==false;var rootMetaObject=loadMetadata?{id:math.createUUID(),name:"Model",type:"Model"}:null;var metadata=loadMetadata?{id:"",projectId:"",author:"",createdAt:"",schema:data.version||"",creatingApplication:"",metaObjects:[rootMetaObject],propertySets:[]}:null;var ctx={data:data,vertices:vertices,sceneModel:sceneModel,loadMetadata:loadMetadata,metadata:metadata,rootMetaObject:rootMetaObject,nextId:0,stats:stats};this._parseCityJSON(ctx);sceneModel.finalize();if(loadMetadata){var metaModelId=sceneModel.id;this.viewer.metaScene.createMetaModel(metaModelId,ctx.metadata,options);}sceneModel.scene.once("tick",function(){if(sceneModel.destroyed){return;}sceneModel.scene.fire("modelLoaded",sceneModel.id);// FIXME: Assumes listeners know order of these two events sceneModel.fire("loaded",true,false);// Don't forget the event, for late subscribers -});}},{key:"_transformVertices",value:function _transformVertices(vertices,transform,rotateX){var transformedVertices=[];var scale=transform.scale||math.vec3([1,1,1]);var translate=transform.translate||math.vec3([0,0,0]);for(var _i584=0,j=0;_i5840)){return;}var meshIds=[];for(var _i585=0,len=cityObject.geometry.length;_i5850){var themeId=themeIds[0];var theme=geometryMaterial[themeId];if(theme.value!==undefined){objectMaterial=materials[theme.value];}else{var values=theme.values;if(values){surfaceMaterials=[];for(var j=0,lenj=values.length;j0){sceneModel.createEntity({id:objectId,meshIds:meshIds,isObject:true});ctx.stats.numObjects++;}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function _parseGeometrySurfacesWithOwnMaterials(ctx,geometry,surfaceMaterials,meshIds){var geomType=geometry.type;switch(geomType){case"MultiPoint":break;case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var surfaces=geometry.boundaries;this._parseSurfacesWithOwnMaterials(ctx,surfaceMaterials,surfaces,meshIds);break;case"Solid":var shells=geometry.boundaries;for(var j=0;j0){holes.push(face.length);}var newFace=this._extractLocalIndices(ctx,surface[j],sharedIndices,geometryCfg);face.push.apply(face,_toConsumableArray(newFace));}if(face.length===3){// Triangle +});}},{key:"_transformVertices",value:function _transformVertices(vertices,transform,rotateX){var transformedVertices=[];var scale=transform.scale||math.vec3([1,1,1]);var translate=transform.translate||math.vec3([0,0,0]);for(var _i586=0,j=0;_i5860)){return;}var meshIds=[];for(var _i587=0,len=cityObject.geometry.length;_i5870){var themeId=themeIds[0];var theme=geometryMaterial[themeId];if(theme.value!==undefined){objectMaterial=materials[theme.value];}else{var values=theme.values;if(values){surfaceMaterials=[];for(var j=0,lenj=values.length;j0){sceneModel.createEntity({id:objectId,meshIds:meshIds,isObject:true});ctx.stats.numObjects++;}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function _parseGeometrySurfacesWithOwnMaterials(ctx,geometry,surfaceMaterials,meshIds){var geomType=geometry.type;switch(geomType){case"MultiPoint":break;case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var surfaces=geometry.boundaries;this._parseSurfacesWithOwnMaterials(ctx,surfaceMaterials,surfaces,meshIds);break;case"Solid":var shells=geometry.boundaries;for(var j=0;j0){holes.push(face.length);}var newFace=this._extractLocalIndices(ctx,surface[j],sharedIndices,geometryCfg);face.push.apply(face,_toConsumableArray(newFace));}if(face.length===3){// Triangle geometryCfg.indices.push(face[0]);geometryCfg.indices.push(face[1]);geometryCfg.indices.push(face[2]);}else if(face.length>3){// Polygon // Prepare to triangulate var pList=[];for(var k=0;k0&&geometryCfg.indices.length>0){var meshId=""+ctx.nextId++;sceneModel.createMesh({id:meshId,primitive:"triangles",positions:geometryCfg.positions,indices:geometryCfg.indices,color:objectMaterial&&objectMaterial.diffuseColor?objectMaterial.diffuseColor:[0.8,0.8,0.8],opacity:1.0//opacity: (objectMaterial && objectMaterial.transparency !== undefined) ? (1.0 - objectMaterial.transparency) : 1.0 -});meshIds.push(meshId);ctx.stats.numGeometries++;ctx.stats.numVertices+=geometryCfg.positions.length/3;ctx.stats.numTriangles+=geometryCfg.indices.length/3;}}},{key:"_parseSurfacesWithSharedMaterial",value:function _parseSurfacesWithSharedMaterial(ctx,surfaces,sharedIndices,primitiveCfg){var vertices=ctx.vertices;for(var _i587=0;_i5870){holes.push(boundary.length);}var newBoundary=this._extractLocalIndices(ctx,surfaces[_i587][j],sharedIndices,primitiveCfg);boundary.push.apply(boundary,_toConsumableArray(newBoundary));}if(boundary.length===3){// Triangle +});meshIds.push(meshId);ctx.stats.numGeometries++;ctx.stats.numVertices+=geometryCfg.positions.length/3;ctx.stats.numTriangles+=geometryCfg.indices.length/3;}}},{key:"_parseSurfacesWithSharedMaterial",value:function _parseSurfacesWithSharedMaterial(ctx,surfaces,sharedIndices,primitiveCfg){var vertices=ctx.vertices;for(var _i589=0;_i5890){holes.push(boundary.length);}var newBoundary=this._extractLocalIndices(ctx,surfaces[_i589][j],sharedIndices,primitiveCfg);boundary.push.apply(boundary,_toConsumableArray(newBoundary));}if(boundary.length===3){// Triangle primitiveCfg.indices.push(boundary[0]);primitiveCfg.indices.push(boundary[1]);primitiveCfg.indices.push(boundary[2]);}else if(boundary.length>3){// Polygon -var pList=[];for(var k=0;k0&&arguments[0]!==undefined?arguments[0]:{};if(params.id&&this.viewer.scene.components[params.id]){this.error("Component with this ID already exists in viewer: "+params.id+" - will autogenerate this ID");delete params.id;}var sceneModel=new SceneModel(this.viewer.scene,utils.apply(params,{isModel:true,backfaces:params.backfaces,dtxEnabled:params.dtxEnabled,rotation:params.rotation,origin:params.origin}));var modelId=sceneModel.id;// In case ID was auto-generated if(!params.src&&!params.dotBIM){this.error("load() param expected: src or dotBIM");return sceneModel;// Return new empty model -}var objectDefaults=params.objectDefaults||this._objectDefaults||IFCObjectDefaults;var includeTypes;if(params.includeTypes){includeTypes={};for(var _i590=0,len=params.includeTypes.length;_i590=0;anglesSum+=convex?_angle3:2*Math.PI-_angle3;}return anglesSum0||d2>0||d3>0;return!(has_neg&&has_pos);};}();var baseTriangles=[];var vertices=(isCCW?polygonVertices:polygonVertices.slice(0).reverse()).map(function(i){return{idx:i};});vertices.forEach(function(v,i){v.prev=vertices[(i-1+vertices.length)%vertices.length];v.next=vertices[(i+1)%vertices.length];});var ba=math.vec2();var bc=math.vec2();while(vertices.length>2){var earIdx=0;var _loop8=function _loop8(){if(earIdx>=vertices.length){throw"isCCW = ".concat(isCCW,"; earIdx = ").concat(earIdx,"; len = ").concat(vertices.length);}var v=vertices[earIdx];var a=planeCoords[v.prev.idx];var b=planeCoords[v.idx];var c=planeCoords[v.next.idx];math.subVec2(a,b,ba);math.subVec2(c,b,bc);if(ba[0]*bc[1]-ba[1]*bc[0]>=0// a convex vertex + */},{key:"destroy",value:function destroy(){_get(_getPrototypeOf(DotBIMLoaderPlugin.prototype),"destroy",this).call(this);}}]);return DotBIMLoaderPlugin;}(Plugin);var hex2rgb=function hex2rgb(color){var rgb=function rgb(idx){return parseInt(color.substr(idx+1,2),16)/255;};return[rgb(0),rgb(2),rgb(4)];};var transformToNode=function transformToNode(from,to,vec){var fromRec=from.getBoundingClientRect();var toRec=to.getBoundingClientRect();vec[0]+=fromRec.left-toRec.left;vec[1]+=fromRec.top-toRec.top;};var triangulateEarClipping=function triangulateEarClipping(planeCoords){var polygonVertices=[];for(var _i596=0;_i596=0;anglesSum+=convex?_angle3:2*Math.PI-_angle3;}return anglesSum0||d2>0||d3>0;return!(has_neg&&has_pos);};}();var baseTriangles=[];var vertices=(isCCW?polygonVertices:polygonVertices.slice(0).reverse()).map(function(i){return{idx:i};});vertices.forEach(function(v,i){v.prev=vertices[(i-1+vertices.length)%vertices.length];v.next=vertices[(i+1)%vertices.length];});var ba=math.vec2();var bc=math.vec2();while(vertices.length>2){var earIdx=0;var _loop8=function _loop8(){if(earIdx>=vertices.length){throw"isCCW = ".concat(isCCW,"; earIdx = ").concat(earIdx,"; len = ").concat(vertices.length);}var v=vertices[earIdx];var a=planeCoords[v.prev.idx];var b=planeCoords[v.idx];var c=planeCoords[v.next.idx];math.subVec2(a,b,ba);math.subVec2(c,b,bc);if(ba[0]*bc[1]-ba[1]*bc[0]>=0// a convex vertex &&vertices.every(// no other vertices inside function(vv){return vv===v||vv===v.prev||vv===v.next||!pointInTriangle(planeCoords[vv.idx],a,b,c);}))return"break";++earIdx;};while(true){var _ret2=_loop8();if(_ret2==="break")break;}var ear=vertices[earIdx];vertices.splice(earIdx,1);baseTriangles.push([ear.idx,ear.next.idx,ear.prev.idx]);var prev=ear.prev;prev.next=ear.next;var next=ear.next;next.prev=ear.prev;}return[planeCoords,baseTriangles];};var draggableDot3D=function draggableDot3D(handleMouseEvents,handleTouchEvents,viewer,worldPos,color,ray2WorldPos,onStart,onMove,onEnd){var scene=viewer.scene;var canvas=scene.canvas.canvas;var marker=new Marker(scene,{});var pickWorldPos=function pickWorldPos(canvasPos){var origin=math.vec3();var direction=math.vec3();math.canvasPosToWorldRay(canvas,scene.camera.viewMatrix,scene.camera.projMatrix,canvasPos,origin,direction);return ray2WorldPos(origin,direction);};var onChange=function onChange(event){var canvasPos=math.vec2([event.clientX,event.clientY]);transformToNode(canvas.ownerDocument.body,canvas,canvasPos);var worldPos=pickWorldPos(canvasPos);marker.worldPos=worldPos;updateDotPos();onMove(canvasPos,worldPos);};var currentDrag=null;var onDragMove=function onDragMove(event){var e=currentDrag.matchesEvent(event);if(e){onChange(e);}};var onDragEnd=function onDragEnd(event){var e=currentDrag.matchesEvent(event);if(e){dot.setOpacity(idleOpacity);currentDrag.cleanup();onChange(e);onEnd();}};var startDrag=function startDrag(matchesEvent,cleanupHandlers){if(currentDrag){currentDrag.cleanup();}dot.setOpacity(1.0);dot.setClickable(false);viewer.cameraControl.active=false;currentDrag={matchesEvent:matchesEvent,cleanup:function cleanup(){currentDrag=null;dot.setClickable(true);viewer.cameraControl.active=true;cleanupHandlers();}};onStart();};var dotCfg={fillColor:color};if(handleMouseEvents){dotCfg.onMouseOver=function(){return!currentDrag&&dot.setOpacity(1.0);};dotCfg.onMouseLeave=function(){return!currentDrag&&dot.setOpacity(idleOpacity);};dotCfg.onMouseDown=function(event){if(event.which===1){canvas.addEventListener("mousemove",onDragMove);canvas.addEventListener("mouseup",onDragEnd);startDrag(function(event){return event.which===1&&event;},function(){canvas.removeEventListener("mousemove",onDragMove);canvas.removeEventListener("mouseup",onDragEnd);});}};}if(handleTouchEvents){var touchStartId;dotCfg.onTouchstart=function(event){event.preventDefault();if(event.touches.length===1){touchStartId=event.touches[0].identifier;startDrag(function(event){return _toConsumableArray(event.changedTouches).find(function(e){return e.identifier===touchStartId;});},function(){touchStartId=null;});}};dotCfg.onTouchmove=function(event){event.preventDefault();onDragMove(event);};dotCfg.onTouchend=function(event){event.preventDefault();onDragEnd(event);};}var dotParent=canvas.ownerDocument.body;var dot=new Dot(dotParent,dotCfg);var idleOpacity=0.5;dot.setOpacity(idleOpacity);var updateDotPos=function updateDotPos(){var pos=marker.canvasPos.slice();transformToNode(canvas,dotParent,pos);dot.setPos(pos[0],pos[1]);};marker.worldPos=worldPos;updateDotPos();var onViewMatrix=scene.camera.on("viewMatrix",updateDotPos);var onProjMatrix=scene.camera.on("projMatrix",updateDotPos);return{setActive:function setActive(value){return dot.setClickable(value);},getWorldPos:function getWorldPos(){return marker.worldPos;},setWorldPos:function setWorldPos(pos){marker.worldPos=pos;updateDotPos();},destroy:function destroy(){currentDrag&¤tDrag.cleanup();scene.camera.off(onViewMatrix);scene.camera.off(onProjMatrix);marker.destroy();dot.destroy();}};};var marker3D=function marker3D(scene,color){var canvas=scene.canvas.canvas;var markerParent=canvas.parentNode;var markerDiv=document.createElement("div");markerParent.insertBefore(markerDiv,canvas);var size=5;markerDiv.style.background=color;markerDiv.style.border="2px solid white";markerDiv.style.margin="0 0";markerDiv.style.zIndex="100";markerDiv.style.position="absolute";markerDiv.style.pointerEvents="none";markerDiv.style.display="none";var marker=new Marker(scene,{});var px=function px(x){return x+"px";};var _update=function update(){var pos=marker.canvasPos.slice();transformToNode(canvas,markerParent,pos);markerDiv.style.left=px(pos[0]-3-size/2);markerDiv.style.top=px(pos[1]-3-size/2);markerDiv.style.borderRadius=px(size*2);markerDiv.style.width=px(size);markerDiv.style.height=px(size);};var onViewMatrix=scene.camera.on("viewMatrix",_update);var onProjMatrix=scene.camera.on("projMatrix",_update);return{update:function update(worldPos){if(worldPos){marker.worldPos=worldPos;_update();}markerDiv.style.display=worldPos?"":"none";},setHighlighted:function setHighlighted(h){size=h?10:5;_update();},getCanvasPos:function getCanvasPos(){return marker.canvasPos;},getWorldPos:function getWorldPos(){return marker.worldPos;},destroy:function destroy(){markerDiv.parentNode.removeChild(markerDiv);scene.camera.off(onViewMatrix);scene.camera.off(onProjMatrix);marker.destroy();}};};var wire3D=function wire3D(scene,color,startWorldPos){var canvas=scene.canvas.canvas;var startMarker=new Marker(scene,{});startMarker.worldPos=startWorldPos;var endMarker=new Marker(scene,{});var wireParent=canvas.ownerDocument.body;var wire=new Wire(wireParent,{color:color,thickness:1,thicknessClickable:6});wire.setVisible(false);var updatePos=function updatePos(){var p0=startMarker.canvasPos.slice();var p1=endMarker.canvasPos.slice();transformToNode(canvas,wireParent,p0);transformToNode(canvas,wireParent,p1);wire.setStartAndEnd(p0[0],p0[1],p1[0],p1[1]);};var onViewMatrix=scene.camera.on("viewMatrix",updatePos);var onProjMatrix=scene.camera.on("projMatrix",updatePos);return{update:function update(endWorldPos){if(endWorldPos){endMarker.worldPos=endWorldPos;updatePos();}wire.setVisible(!!endWorldPos);},destroy:function destroy(){scene.camera.off(onViewMatrix);scene.camera.off(onProjMatrix);startMarker.destroy();endMarker.destroy();wire.destroy();}};};var basePolygon3D=function basePolygon3D(scene,color,alpha){var mesh=null;var updateBase=function updateBase(points){if(points){if(mesh){mesh.destroy();}try{var _ref22,_ref23;var _triangulateEarClippi=triangulateEarClipping(points.map(function(p){return[p[0],p[2]];})),_triangulateEarClippi2=_slicedToArray(_triangulateEarClippi,2),baseVertices=_triangulateEarClippi2[0],baseTriangles=_triangulateEarClippi2[1];var positions=(_ref22=[]).concat.apply(_ref22,_toConsumableArray(baseVertices.map(function(p){return[p[0],points[0][1],p[1]];})));// To convert from Float64Array into an Array var ind=(_ref23=[]).concat.apply(_ref23,_toConsumableArray(baseTriangles));mesh=new Mesh(scene,{pickable:false,// otherwise there's a WebGL error inside PickMeshRenderer.prototype.drawMesh @@ -30012,12 +30018,12 @@ var onCanvasTouchMove=function onCanvasTouchMove(event){var touch=_toConsumableA var pos=[];var ind=[];var addPlane=function addPlane(isCeiling){var baseIdx=pos.length;var _iterator41=_createForOfIteratorHelper(baseVertices),_step41;try{for(_iterator41.s();!(_step41=_iterator41.n()).done;){var c=_step41.value;pos.push([c[0],altitude+(isCeiling?height:0),c[1]]);}}catch(err){_iterator41.e(err);}finally{_iterator41.f();}var _iterator42=_createForOfIteratorHelper(baseTriangles),_step42;try{for(_iterator42.s();!(_step42=_iterator42.n()).done;){var t=_step42.value;ind.push.apply(ind,_toConsumableArray((isCeiling?t:t.slice(0).reverse()).map(function(i){return i+baseIdx;})));}}catch(err){_iterator42.e(err);}finally{_iterator42.f();}};addPlane(false);// floor addPlane(true);// ceiling // sides -var _loop9=function _loop9(_i596){var a=baseVertices[_i596];var b=baseVertices[(_i596+1)%baseVertices.length];var f=altitude;var c=altitude+height;var baseIdx=pos.length;pos.push([a[0],f,a[1]],[b[0],f,b[1]],[b[0],c,b[1]],[a[0],c,a[1]]);ind.push.apply(ind,_toConsumableArray([0,1,2,0,2,3].map(function(i){return i+baseIdx;})));};for(var _i596=0;_i596_EPSILON?FRONT:COPLANAR;polygonType|=type;types.push(type);}// Put the polygon in the correct list, splitting it when necessary. -switch(polygonType){case COPLANAR:newFaces.push(face);break;case FRONT:newFaces.push(face);break;case BACK:break;case SPANNING:var _f4=[];for(var _i599=0;_i599=3){newFaces.push(_f4);}break;}}}catch(err){_iterator46.e(err);}finally{_iterator46.f();}faces=newFaces;}}catch(err){_iterator43.e(err);}finally{_iterator43.f();}if(faces.length===0){return null;}else{var avg=math.vec3([0,0,0]);var unique=new Set();var _iterator44=_createForOfIteratorHelper(faces),_step44;try{for(_iterator44.s();!(_step44=_iterator44.n()).done;){var _f3=_step44.value;var _iterator45=_createForOfIteratorHelper(_f3),_step45;try{for(_iterator45.s();!(_step45=_iterator45.n()).done;){var _p5=_step45.value;var id=_p5.map(function(x){return x.toFixed(3);}).join(":");if(!unique.has(id)){unique.add(id);math.addVec3(avg,_p5,avg);}}}catch(err){_iterator45.e(err);}finally{_iterator45.f();}}}catch(err){_iterator44.e(err);}finally{_iterator44.f();}math.mulVec3Scalar(avg,1/unique.size,avg);return avg;}}},{key:"center",get:function get(){return this._center;}},{key:"altitude",get:function get(){return this._geometry.altitude;},set:function set(value){this._geometry.altitude=value;this._rebuildMesh();}},{key:"height",get:function get(){return this._geometry.height;},set:function set(value){this._geometry.height=value;this._rebuildMesh();}},{key:"highlighted",get:function get(){return this._highlighted;},set:function set(value){this._highlighted=value;if(this._zoneMesh){this._zoneMesh.highlighted=value;}}},{key:"color",get:function get(){return this._color;},set:function set(value){this._color=value;if(this._zoneMesh){this._zoneMesh.material.diffuse=hex2rgb(this._color);}}},{key:"alpha",get:function get(){return this._alpha;},set:function set(value){this._alpha=value;if(this._zoneMesh){this._zoneMesh.material.alpha=this._alpha;}}},{key:"edges",get:function get(){return this._edges;},set:function set(edges){this._edges=edges;if(this._zoneMesh){this._zoneMesh.edges=this._edges;}}/** +var _p4=function _p4(idx,y){return[planeCoords[idx][0],y,planeCoords[idx][1]];};for(var _i599=0;_i599_EPSILON?FRONT:COPLANAR;polygonType|=type;types.push(type);}// Put the polygon in the correct list, splitting it when necessary. +switch(polygonType){case COPLANAR:newFaces.push(face);break;case FRONT:newFaces.push(face);break;case BACK:break;case SPANNING:var _f4=[];for(var _i601=0;_i601=3){newFaces.push(_f4);}break;}}}catch(err){_iterator46.e(err);}finally{_iterator46.f();}faces=newFaces;}}catch(err){_iterator43.e(err);}finally{_iterator43.f();}if(faces.length===0){return null;}else{var avg=math.vec3([0,0,0]);var unique=new Set();var _iterator44=_createForOfIteratorHelper(faces),_step44;try{for(_iterator44.s();!(_step44=_iterator44.n()).done;){var _f3=_step44.value;var _iterator45=_createForOfIteratorHelper(_f3),_step45;try{for(_iterator45.s();!(_step45=_iterator45.n()).done;){var _p5=_step45.value;var id=_p5.map(function(x){return x.toFixed(3);}).join(":");if(!unique.has(id)){unique.add(id);math.addVec3(avg,_p5,avg);}}}catch(err){_iterator45.e(err);}finally{_iterator45.f();}}}catch(err){_iterator44.e(err);}finally{_iterator44.f();}math.mulVec3Scalar(avg,1/unique.size,avg);return avg;}}},{key:"center",get:function get(){return this._center;}},{key:"altitude",get:function get(){return this._geometry.altitude;},set:function set(value){this._geometry.altitude=value;this._rebuildMesh();}},{key:"height",get:function get(){return this._geometry.height;},set:function set(value){this._geometry.height=value;this._rebuildMesh();}},{key:"highlighted",get:function get(){return this._highlighted;},set:function set(value){this._highlighted=value;if(this._zoneMesh){this._zoneMesh.highlighted=value;}}},{key:"color",get:function get(){return this._color;},set:function set(value){this._color=value;if(this._zoneMesh){this._zoneMesh.material.diffuse=hex2rgb(this._color);}}},{key:"alpha",get:function get(){return this._alpha;},set:function set(value){this._alpha=value;if(this._zoneMesh){this._zoneMesh.material.alpha=this._alpha;}}},{key:"edges",get:function get(){return this._edges;},set:function set(edges){this._edges=edges;if(this._zoneMesh){this._zoneMesh.edges=this._edges;}}/** * Sets whether this Zone is visible or not. * * @type {Boolean} @@ -30105,7 +30111,7 @@ switch(polygonType){case COPLANAR:newFaces.push(face);break;case FRONT:newFaces. */},{key:"destroy",value:function destroy(){_get(_getPrototypeOf(ZonesPlugin.prototype),"destroy",this).call(this);}}]);return ZonesPlugin;}(Plugin);var ZonesTouchControl=/*#__PURE__*/function(_Component42){_inherits(ZonesTouchControl,_Component42);var _super170=_createSuper(ZonesTouchControl);function ZonesTouchControl(zonesPlugin){var _this179;var cfg=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck(this,ZonesTouchControl);_this179=_super170.call(this,zonesPlugin.viewer.scene);_this179.zonesPlugin=zonesPlugin;_this179.pointerLens=cfg.pointerLens;_this179.pointerCircle=new PointerCircle(zonesPlugin.viewer);_this179._deactivate=null;return _this179;}_createClass(ZonesTouchControl,[{key:"active",get:function get(){return!!this._deactivate;}},{key:"activate",value:function activate(zoneAltitude,zoneHeight,zoneColor,zoneAlpha){if(_typeof(zoneAltitude)==="object"&&zoneAltitude!==null){var params=zoneAltitude;var param=function param(name,defaultValue){if(name in params){return params[name];}else if(defaultValue!==undefined){return defaultValue;}else{throw"config missing: "+name;}};zoneAltitude=param("altitude");zoneHeight=param("height");zoneColor=param("color","#008000");zoneAlpha=param("alpha",0.5);}if(this._deactivate){return;}var zonesPlugin=this.zonesPlugin;var viewer=zonesPlugin.viewer;var scene=viewer.scene;var self=this;var select3dPoint=touchPointSelector(viewer,this.pointerCircle,function(origin,direction){return planeIntersect(zoneAltitude,math.vec3([0,1,0]),origin,direction);});(function rec(){self._deactivate=startAAZoneCreateUI(scene,zoneAltitude,zoneHeight,zoneColor,zoneAlpha,self.pointerLens,zonesPlugin,select3dPoint,function(zone){var reactivate=true;self._deactivate=function(){reactivate=false;};self.fire("zoneEnd",zone);if(reactivate){rec();}}).deactivate;})();}},{key:"deactivate",value:function deactivate(){if(this._deactivate){this._deactivate();this._deactivate=null;}}},{key:"destroy",value:function destroy(){this.deactivate();_get(_getPrototypeOf(ZonesTouchControl.prototype),"destroy",this).call(this);}}]);return ZonesTouchControl;}(Component);var startPolysurfaceZoneCreateUI=function startPolysurfaceZoneCreateUI(scene,zoneAltitude,zoneHeight,zoneColor,zoneAlpha,pointerLens,zonesPlugin,select3dPoint,onZoneCreated){var updatePointerLens=pointerLens?function(canvasPos){pointerLens.visible=!!canvasPos;if(canvasPos){pointerLens.canvasPos=canvasPos;}}:function(){};var deactivatePointSelection;var cleanups=[function(){return updatePointerLens(null);}];var basePolygon=basePolygon3D(scene,zoneColor,zoneAlpha);cleanups.push(function(){return basePolygon.destroy();});(function selectNextPoint(markers){var marker=marker3D(scene,zoneColor);var wire=markers.length>0&&wire3D(scene,zoneColor,markers[markers.length-1].getWorldPos());cleanups.push(function(){marker.destroy();wire&&wire.destroy();});var firstMarker=markers.length>0&&markers[0];var getSnappedFirst=function getSnappedFirst(canvasPos){var firstCanvasPos=firstMarker&&firstMarker.getCanvasPos();var snapToFirst=firstCanvasPos&&math.distVec2(firstCanvasPos,canvasPos)<10;return snapToFirst&&{canvasPos:firstCanvasPos,worldPos:firstMarker.getWorldPos()};};var lastSegmentIntersects=function(){var onSegment=function onSegment(p,q,r){return q[0]<=Math.max(p[0],r[0])&&q[0]>=Math.min(p[0],r[0])&&q[1]<=Math.max(p[1],r[1])&&q[1]>=Math.min(p[1],r[1]);};var orient=function orient(p,q,r){var val=(q[1]-p[1])*(r[0]-q[0])-(q[0]-p[0])*(r[1]-q[1]);// collinear // clockwise // counterclockwise -return val===0?0:val>0?1:2;};return function(pos2D,excludeFirstSegment){var a=pos2D[pos2D.length-2];var b=pos2D[pos2D.length-1];for(var _i600=excludeFirstSegment?1:0;_i6000?1:2;};return function(pos2D,excludeFirstSegment){var a=pos2D[pos2D.length-2];var b=pos2D[pos2D.length-1];for(var _i602=excludeFirstSegment?1:0;_i602o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],L=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+L*f,i[13]=D*r+S*l+T*u+L*g,i[14]=D*o+S*A+T*d+L*m,i[15]=D*n+S*h+T*p+L*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-x*P+B*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-u,g=n-d,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(16),i=new n(4),s=new n(4),r=new n(4),o=new n(4);return(n,a,l,A,h,u)=>{const d=c.mulMat4(l,a,e),p=c.inverseMat4(d,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,c.transformVec4(p,i,s),c.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,c.transformVec4(p,r,o),c.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],c.subVec3(o,s,u),c.normalizeVec3(u)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l)=>{c.canvasPosToWorldRay(i,s,r,n,e,t),c.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[E.index1],L=i[E.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in x.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];x.sceneId=t,x.startTime=i.startTime,x.deltaTime=null!=x.prevTime?x.time-x.prevTime:0,i.fire("tick",x,!0)}x.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new R,new R,new R,new R,new R,new R]}}function k(e,t,i){const s=c.mulMat4(i,t,L),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function O(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=O(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),k(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}class V{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H=c.vec3(),j=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function G(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function z(e,t,i,s=1e3){const r=c.getPositionsCenter(e,H),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){oe.set(this._viewPos),oe[3]=1,c.transformPoint4(this.scene.camera.projMatrix,oe,ne);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ne[0]/ne[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ne[1]/ne[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof re?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),G(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const le={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class Ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class he{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ce{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ue=c.vec3(),de=c.vec3();class pe extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originMarker=new ae(i,t.origin),this._cornerMarker=new ae(i,t.corner),this._targetMarker=new ae(i,t.target),this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new Ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new Ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new ce(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>d||f>d||g>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&u(e.offsetParent)),d=c.vec2();this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,d),this.markerDiv.style.left=d[0]-5+"px",this.markerDiv.style.top=d[1]-5+"px"):(this.markerDiv.style.left=u(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class me extends ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

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

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const _e=c.vec3(),ve=c.vec3(),be=c.vec3();class ye extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const xe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Be extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new ye(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+c.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Pe.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Pe.FS_MAX_FLOAT_PRECISION="mediump":Pe.FS_MAX_FLOAT_PRECISION="lowp":Pe.FS_MAX_FLOAT_PRECISION="mediump",Pe.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Pe.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Pe.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Pe.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Pe.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Pe.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Pe.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Pe.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Pe.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Pe.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Pe.SUPPORTED_EXTENSIONS[e]=!0})))}class Me{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Fe{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Te(e){console.error(e.join("\n"))}class Le{constructor(e,t){this.id=De.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Fe(e,e.VERTEX_SHADER,Se(this.source.vertex)),this._fragmentShader=new Fe(e,e.FRAGMENT_SHADER,Se(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Te(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Te(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Te(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Te(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void Te(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ue{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Ue(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Ue(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Le(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;Qe[0]=o,Qe[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Qe),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Le(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Re(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Re(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Re(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const He=new Float32Array(Xe(17,[0,1])),je=new Float32Array(Xe(17,[1,0])),Ge=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(Ke(s,t));return i}(17,4)),ze=new Float32Array(2);class We{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Le(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Re(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Re(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Re(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),ze[0]=n,ze[1]=a,s.uniform2fv(this._uViewport,ze),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,je):s.uniform2fv(this._uSampleOffsets,He),s.uniform1fv(this._uSampleWeights,Ge);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ke(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Xe(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class Je{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Ye{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new Je(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Ze(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const qe=function(t,i){i=i||{};const s=new we(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=!0,d=!0,f=!0,g=!0,m=!0,_=!0,v=!0,b=!0;const y=new Ye(t);let x=!1;const B=new Ve(t),w=new We(t);function P(){u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),u=!1,d=!0),d&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),d=!1,f=!0),f&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||O>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(O>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||K>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),K>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),J>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=d.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,L=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),L=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===x&&null==D)return null;let R=null;null!==D&&(R=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===L,h.snappedToVertex="vertex"===L,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=R||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ne(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const et=new e({});class tt{constructor(e){this.id=et.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){et.removeItem(this.id)}}class it extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new tt({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class st extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class rt extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ot extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){c.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class nt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const at=c.vec3(),lt=c.vec3(),At=c.vec3(),ht=c.vec3(),ct=c.vec3(),ut=c.vec3(),dt=c.vec4(),pt=c.vec4(),ft=c.vec4(),gt=c.mat4(),mt=c.mat4(),_t=c.vec3(),vt=c.vec3(),bt=c.vec3(),yt=c.vec3();class xt extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new tt({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new st(this),this._ortho=new rt(this),this._frustum=new ot(this),this._customProjection=new nt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(c.subVec3(this._eye,this._look,_t),c.normalizeVec3(_t,vt),c.mulVec3Scalar(vt,1e3,bt),c.addVec3(this._look,bt,yt),t=yt):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,mt),c.mulMat4(e.deviceMatrix,mt,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=c.subVec3(this._eye,this._look,at);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,gt),t=c.transformPoint3(gt,t,lt),this.eye=c.addVec3(this._look,t,At),this.up=c.transformPoint3(gt,this._up,ht)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,at);const i=c.cross3Vec3(c.normalizeVec3(t,lt),c.normalizeVec3(this._up,At));c.rotationMat4v(.0174532925*e,i,gt),t=c.transformPoint3(gt,t,ht),this.up=c.transformPoint3(gt,this._up,ct),this.eye=c.addVec3(t,this._look,ut)}yaw(e){let t=c.subVec3(this._look,this._eye,at);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,gt),t=c.transformPoint3(gt,t,lt),this.look=c.addVec3(t,this._eye,At),this._gimbalLock&&(this.up=c.transformPoint3(gt,this._up,ht))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,at);const i=c.cross3Vec3(c.normalizeVec3(t,lt),c.normalizeVec3(this._up,At));c.rotationMat4v(.0174532925*e,i,gt),this.up=c.transformPoint3(gt,this._up,ut),t=c.transformPoint3(gt,t,ht),this.look=c.addVec3(t,this._eye,ct)}pan(e){const t=c.subVec3(this._eye,this._look,at),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,lt));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,At),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,ht),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,ct),this.look=c.addVec3(this._look,i,ut)}zoom(e){const t=c.subVec3(this._eye,this._look,at),i=Math.abs(c.lenVec3(t,lt)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,At);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),ht)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=c.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return c.lenVec3(c.subVec3(this._look,this._eye,at))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=dt,i=pt,s=ft;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Bt extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class wt extends Bt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new tt({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Je(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Pt extends Bt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Ct extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Mt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[E.index1],L=i[E.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}();const Ft=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Et=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function St(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Tt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Lt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Dt(e,a,"floor","ceil"),s=St(i),o=Tt(e,a,s),o>n&&(r=i,n=o),i=Dt(e,a,"ceil","ceil"),s=St(i),o=Tt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Rt=p.memory,Ut=c.AABB3();class kt extends Ct{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new tt({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Lt.getPositionsBounds(t.positions),s=Lt.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Lt.getUVBounds(t.uv),s=Lt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Lt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Rt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Rt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Re(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Rt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Re(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Rt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Re(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Rt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Re(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Rt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Mt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Rt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Re(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Rt.positions+=this._pickTrianglePositionsBuf.numItems,Rt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Lt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Lt.getPositionsBounds(e),s=Lt.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Lt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Lt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,Ut,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(Ut,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Rt.meshes--}}function Ot(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Nt extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Qt={opaque:0,mask:1,blend:2},Vt=["opaque","mask","blend"];class Ht extends Nt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new tt({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Qt[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 Vt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Gt extends Nt{get type(){return"EmphasisMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new tt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const zt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Wt extends Nt{get type(){return"EdgeMaterial"}get presets(){return zt}constructor(e,t={}){super(e,t),this._state=new tt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=zt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(zt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Kt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Xt extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Kt}set units(e){e||(e="meters");Kt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Jt extends D{constructor(e,t={}){super(e,t),this._supported=Pe.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class Yt extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const Zt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class qt extends Nt{get type(){return"PointsMaterial"}get presets(){return Zt}constructor(e,t={}){super(e,t),this._state=new tt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=Zt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Zt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const $t={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ei extends Nt{get type(){return"LinesMaterial"}get presets(){return $t}constructor(e,t={}){super(e,t),this._state=new tt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=$t[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys($t).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function ti(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new qe(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=c.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=ti(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ti(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const si=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=ni(e),u=s.getNumAllocatedSectionPlanes()>0,d=oi(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=ni(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=oi(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ri[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ri[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ri[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ri[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ri[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ri[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class ci{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ui=new e({}),di=c.vec3(),pi=function(e,t){this.id=ui.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ci(t),this._allocate(t)},fi={};pi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=fi[t];return i||(i=new pi(t,e),fi[t]=i,p.memory.programs++),i._useCount++,i},pi.prototype.put=function(){0==--this._useCount&&(ui.removeItem(this.id),this._program&&this._program.destroy(),delete fi[this._hash],p.memory.programs--)},pi.prototype.webglContextRestored=function(){this._program=null},pi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const mi=new e({}),_i=c.vec3(),vi=function(e,t){this.id=mi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new gi(t),this._allocate(t)},bi={};vi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=bi[t];return i||(i=new vi(t,e),bi[t]=i,p.memory.programs++),i._useCount++,i},vi.prototype.put=function(){0==--this._useCount&&(mi.removeItem(this.id),this._program&&this._program.destroy(),delete bi[this._hash],p.memory.programs--)},vi.prototype.webglContextRestored=function(){this._program=null},vi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const xi=c.vec3(),Bi=function(e,t){this._hash=e,this._shaderSource=new yi(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},wi={};Bi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=wi[t];if(!i){if(i=new Bi(t,e),i.errors)return console.log(i.errors.join("\n")),null;wi[t]=i,p.memory.programs++}return i._useCount++,i},Bi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete wi[this._hash],p.memory.programs--)},Bi.prototype.webglContextRestored=function(){this._program=null},Bi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Bi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Le(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Ci=c.vec3(),Mi=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Pi(t),this._allocate(t)},Fi={};Mi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Fi[t];if(!i){if(i=new Mi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Fi[t]=i,p.memory.programs++}return i._useCount++,i},Mi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Fi[this._hash],p.memory.programs--)},Mi.prototype.webglContextRestored=function(){this._program=null},Mi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Ii=c.vec3(),Di=function(e,t){this._hash=e,this._shaderSource=new Ei(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Si={};Di.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Si[t];if(!i){if(i=new Di(t,e),i.errors)return console.log(i.errors.join("\n")),null;Si[t]=i,p.memory.programs++}return i._useCount++,i},Di.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Si[this._hash],p.memory.programs--)},Di.prototype.webglContextRestored=function(){this._program=null},Di.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Li=function(e,t){this._hash=e,this._shaderSource=new Ti(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ri={};Li.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Ri[i];if(!s){if(s=new Li(i,e),s.errors)return console.log(s.errors.join("\n")),null;Ri[i]=s,p.memory.programs++}return s._useCount++,s},Li.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ri[this._hash],p.memory.programs--)},Li.prototype.webglContextRestored=function(){this._program=null},Li.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Li.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Le(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Xi=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),x=c.vec3(),B=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),F=c.vec3(),E=c.vec3(),I=c.vec3();return function(D,S,T,L){var R=L.primIndex;if(null!=R&&R>-1){const N=D.geometry._state,Q=D.scene,V=Q.camera,H=Q.canvas;if("triangles"===N.primitiveName){L.primitive="triangle";const Q=R,G=N.indices,z=N.positions;let W,K,X;if(G){var U=G[Q+0],k=G[Q+1],O=G[Q+2];o[0]=U,o[1]=k,o[2]=O,L.indices=o,W=3*U,K=3*k,X=3*O}else W=3*Q,K=W+3,X=K+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[K+0],s[1]=z[K+1],s[2]=z[K+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Lt.decompressPosition(i,e,i),Lt.decompressPosition(s,e,s),Lt.decompressPosition(r,e,r))}L.canvasPos?c.canvasPosToLocalRay(H.canvas,D.origin?j(S,D.origin):S,T,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&c.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,c.transformVec4(V.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*k,i=3*O;Lt.decompressNormal(J.subarray(e,e+2),h),Lt.decompressNormal(J.subarray(t,t+2),u),Lt.decompressNormal(J.subarray(i,i+2),d)}else h[0]=J[W],h[1]=J[W+1],h[2]=J[W+2],u[0]=J[K],u[1]=J[K+1],u[2]=J[K+2],d[0]=J[X],d[1]=J[X+1],d[2]=J[X+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),x),c.mulVec3Scalar(d,A[2],B),w);L.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*k],f[1]=Y[2*k+1],g[0]=Y[2*O],g[1]=Y[2*O+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Lt.decompressUV(p,e,p),Lt.decompressUV(f,e,f),Lt.decompressUV(g,e,g))}L.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),F),c.mulVec2Scalar(g,A[2],E),I)}}}}}();function Ji(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,x,B,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),v.push(x*p),v.push(1*y/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{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 qi(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,x=.04,B=0;B0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ms(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ms(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ms(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ys(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ys(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ms(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ms(i,this.magFilter)));const a=ms(i,this.format,this.encoding),l=ms(i,this.type),A=bs(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Ps extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new tt({texture:new vs({gl:this.scene.canvas.gl}),matrix:c.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new vs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=xs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=xs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const Cs=p.memory,Ms=c.AABB3();class Fs extends Ct{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new tt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Lt.getPositionsBounds(t.positions),o=Lt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Re(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Cs.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,Ms,i.positionsDecodeMatrix),c.AABB3ToOBB3(Ms,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Re(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Cs.colors+=i.colorsBuf.numItems}if(t.uv){const e=Lt.getUVBounds(t.uv),r=Lt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Re(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Cs.uvs+=i.uvBuf.numItems}if(t.normals){const e=Lt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Re(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Cs.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Cs.indices+=i.indicesBuf.numItems;const o=Mt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Cs.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(),Cs.meshes--}}var Es={};function Is(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Ds(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Ss(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,x,B,w,P,C,M,F=0,E=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-x/s),d.push(B/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Ls(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Es.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Es.parse={},Es.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Rs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Ps(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new As(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new Ki(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new kt(this,Ss({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ht(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const Us=c.OBB3(),ks=c.OBB3(),Os=c.OBB3();class Ns{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=c.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(c.AABB3ToOBB3(this._aabbLocal,Us),this.transform?(c.transformOBB3(this.transform.worldMatrix,Us,ks),c.transformOBB3(this.model.worldMatrix,ks,Os),c.OBB3ToAABB3(Os,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,Us,ks),c.OBB3ToAABB3(ks,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Qs=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 Vs=0;const Hs={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},js=new Float32Array([1,1,1,1]),Gs=new Float32Array([0,0,0,1]),zs=c.vec4(),Ws=c.vec3(),Ks=c.vec3(),Xs=c.mat4();class Js{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;zs[0]=i,zs[1]=s,zs[2]=t.blendCutoff,zs[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,zs),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?Gs:js)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class Ys extends Js{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Zs extends Ys{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class qs extends Ys{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class er extends Ys{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class tr extends er{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ir extends er{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class sr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class rr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class or extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class nr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class ar extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class lr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ar extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class hr extends Ys{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class ur extends Ys{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vr=c.vec3(),br=c.vec3(),yr=c.vec3(),xr=c.vec3(),Br=c.mat4();class wr extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=vr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=br;if(l){const e=yr;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,Br),m=xr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new $s(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new sr(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new rr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _r(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Zs(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Zs(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new qs(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new qs(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ur(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ur(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new hr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new hr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new $s(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ar(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new lr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new tr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ir(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new sr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new or(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ar(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _r(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Cr={};let Mr=65536,Fr=5e6;class Er{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Mr=e}get maxDataTextureHeight(){return Mr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Fr=e}get maxGeometryBatchSize(){return Fr}}const Ir=new Er;class Dr{constructor(){this.maxVerts=Ir.maxGeometryBatchSize,this.maxIndices=3*Ir.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Sr=c.mat4(),Tr=c.mat4();function Lr(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function kr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Or=c.mat4(),Nr=c.mat4(),Qr=c.vec4([0,0,0,1]),Vr=c.vec3(),Hr=c.vec3(),jr=c.vec3(),Gr=c.vec3(),zr=c.vec3(),Wr=c.vec3(),Kr=c.vec3();class Xr{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Cr[t];return i||(i=new Pr(e),Cr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Dr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Or;m?c.inverseMat4(c.transposeMat4(m,Nr),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=Ur(p,"floor","ceil"),a=kr(n),A=o(p,a),A>h&&(l=n,h=A),n=Ur(p,"ceil","ceil"),a=kr(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Lr(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Re(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Re(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Lt.getUVBounds(i.uv),r=Lt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new Re(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Re(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Jr extends Js{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Yr extends Jr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zr extends Jr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class $r extends Jr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class eo extends $r{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class to extends $r{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class io extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class so extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ro extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class oo extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class no extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class ao extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class lo extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ao={3e3:"linearToLinear",3001:"sRGBToLinear"};class ho extends Jr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Ao[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Ao[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class uo extends Jr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const bo=c.vec3(),yo=c.vec3(),xo=c.vec3(),Bo=c.vec3(),wo=c.mat4();class Po extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=bo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=yo;if(l){const e=c.transformPoint3(h,l,xo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,wo),m=Bo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Co{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new io(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new so(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new vo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Po(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zr(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ho(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ho(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new uo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new uo(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new no(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ao(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new eo(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new to(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new io(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ro(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new co(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new so(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new oo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new lo(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new vo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Po(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Mo={};const Fo=new Uint8Array(4),Eo=new Float32Array(1),Io=c.vec4([0,0,0,1]),Do=new Float32Array(3),So=c.vec3(),To=c.vec3(),Lo=c.vec3(),Ro=c.vec3(),Uo=c.vec3(),ko=c.vec3(),Oo=c.vec3(),No=new Float32Array(4);class Qo{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Mo[t];return i||(i=new Co(e),Mo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Mo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Re(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Re(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Re(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Re(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Re(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Re(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Re(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],Fo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Fo,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?1:0)<<16,Eo[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Eo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Do[0]=t[0],Do[1]=t[1],Do[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Do,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],u=Io,d=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Vo extends Js{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Ho extends Vo{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class jo extends Vo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Go=c.vec3(),zo=c.vec3(),Wo=c.vec3(),Ko=c.vec3(),Xo=c.mat4();class Jo extends Js{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Go;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=zo;if(l){const e=Wo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,Xo),m=Ko,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yo=c.vec3(),Zo=c.vec3(),qo=c.vec3(),$o=c.vec3(),en=c.mat4();class tn extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Yo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Zo;if(l){const e=qo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,en),m=$o,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class sn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ho(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new jo(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Jo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new tn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const rn={};class on{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class nn{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=rn[t];return i||(i=new sn(e),rn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete rn[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new on(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Lr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class An extends an{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const hn=c.vec3(),cn=c.vec3(),un=c.vec3();c.vec3();const dn=c.mat4();class pn extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=hn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=cn;if(l){const e=c.transformPoint3(h,l,un);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,dn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fn=c.vec3(),gn=c.vec3(),mn=c.vec3();c.vec3();const _n=c.mat4();class vn extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=fn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=gn;if(l){const e=c.transformPoint3(h,l,mn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,_n),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class bn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new pn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new vn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ln(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new An(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new pn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new vn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const yn={};const xn=new Uint8Array(4),Bn=new Float32Array(1),wn=new Float32Array(3),Pn=new Float32Array(4);class Cn{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=yn[t];return i||(i=new bn(e),yn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete yn[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Re(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Re(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Re(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Re(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],xn[3]=t[3],this._state.colorsBuf.setData(xn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?255:0)<<16,Bn[0]=d,this._state.flagsBuf.setData(Bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(wn[0]=t[0],wn[1]=t[1],wn[2]=t[2],this._state.offsetsBuf.setData(wn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Pn[0]=t[0],Pn[1]=t[4],Pn[2]=t[8],Pn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Pn,i),Pn[0]=t[1],Pn[1]=t[5],Pn[2]=t[9],Pn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Pn,i),Pn[0]=t[2],Pn[1]=t[6],Pn[2]=t[10],Pn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Pn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Mn extends Js{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Fn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class En extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class In extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Dn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Sn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Tn=c.vec3(),Ln=c.vec3(),Rn=c.vec3(),Un=c.vec3(),kn=c.mat4();class On extends Js{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Tn;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ln;if(l){const e=Rn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,kn),m=Un,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Nn=c.vec3(),Qn=c.vec3(),Vn=c.vec3(),Hn=c.vec3(),jn=c.mat4();class Gn extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Nn;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Qn;if(l){const e=Vn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,jn),m=Hn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new In(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sn(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new On(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Gn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Wn={};class Kn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class Xn{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Wn[t];return i||(i=new zn(e),Wn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Wn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Kn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Lr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Zn extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class qn extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class $n extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ea extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ta extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class ia extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const sa=c.vec3(),ra=c.vec3(),oa=c.vec3();c.vec3();const na=c.mat4();class aa extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sa;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ra;if(l){const e=c.transformPoint3(h,l,oa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,na),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const la=c.vec3(),Aa=c.vec3(),ha=c.vec3();c.vec3();const ca=c.mat4();class ua extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=la;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Aa;if(l){const e=c.transformPoint3(h,l,ha);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,ca),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class da{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Zn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ta(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new qn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $n(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ea(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ia(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new aa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ua(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const pa={};const fa=new Uint8Array(4),ga=new Float32Array(1),ma=new Float32Array(3),_a=new Float32Array(4);class va{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=pa[t];return i||(i=new da(e),pa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete pa[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Re(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Re(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Re(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";fa[0]=t[0],fa[1]=t[1],fa[2]=t[2],this._state.colorsBuf.setData(fa,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?255:0)<<16,ga[0]=d,this._state.flagsBuf.setData(ga,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ma[0]=t[0],ma[1]=t[1],ma[2]=t[2],this._state.offsetsBuf.setData(ma,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;_a[0]=t[0],_a[1]=t[4],_a[2]=t[8],_a[3]=t[12],this._state.modelMatrixCol0Buf.setData(_a,i),_a[0]=t[1],_a[1]=t[5],_a[2]=t[9],_a[3]=t[13],this._state.modelMatrixCol1Buf.setData(_a,i),_a[0]=t[2],_a[1]=t[6],_a[2]=t[10],_a[3]=t[14],this._state.modelMatrixCol2Buf.setData(_a,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Hs.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Hs.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const ba=c.vec3(),ya=c.vec3(),xa=c.mat4();class Ba{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ba;if(g){const t=c.transformPoint3(u,A,ya);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,xa)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ba(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Pa={};class Ca{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ma{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Fa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ea={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ea,null,4));let e=0;Object.keys(Ea).forEach((t=>{t.startsWith("size")&&(e+=Ea[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ea.totalLines).toFixed(2)}`);let t={};Object.keys(Ea).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ea[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ia{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ea.sizeDataColorsAndFlags+=l.byteLength,Ea.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ea.sizeDataTextureOffsets+=r.byteLength,Ea.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ea.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Pa[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Ca,this._dataTextureState=new Ma,this._dataTextureGenerator=new Ia,this._state=new tt({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ea.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Sa||t+r>4096*Sa)&&Ea.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Sa&&t+r<=4096*Sa}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ea.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ea.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||ka),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ea.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ea.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ea.totalLines32Bits+=t.numLines),Ea.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,La))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,La))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,La))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ra))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ta))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Na=c.vec3(),Qa=c.vec3(),Va=c.vec3();c.vec3();const Ha=c.vec4(),ja=c.mat4();class Ga{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Na;if(g){const t=c.transformPoint3(u,A,Qa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,ja),f=Va,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Le(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const za=new Float32Array([1,1,1]),Wa=c.vec3(),Ka=c.vec3(),Xa=c.vec3();c.vec3();const Ja=c.mat4();class Ya{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Wa;if(A){const t=Ka;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,Ja),g=Xa,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Hs.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,za);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Za=new Float32Array([0,0,0,1]),qa=c.vec3(),$a=c.vec3();c.vec3();const el=c.mat4();class tl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=qa;if(g){const t=c.transformPoint3(u,A,$a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,el)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Hs.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Za);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const il=c.vec3(),sl=c.vec3(),rl=c.mat4();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,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=il;if(g){const t=c.transformPoint3(u,A,sl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,rl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const nl=c.vec3(),al=c.vec3(),ll=c.vec3(),Al=c.mat4();class hl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=nl;if(g){const t=c.transformPoint3(u,A,al);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(o.viewMatrix,e,Al),f=ll,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const cl=c.vec3(),ul=c.vec3(),dl=c.vec3();c.vec3();const pl=c.mat4();class fl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=cl;if(A){const e=ul;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=j(p,t,pl),g=dl,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gl=c.vec3(),ml=c.vec3(),_l=c.vec3(),vl=c.vec3();c.vec3();const bl=c.mat4();class yl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=gl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ml;if(v){const e=c.transformPoint3(u,A,_l);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=j(f,t,bl),_=vl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xl=c.vec3(),Bl=c.vec3(),wl=c.vec3(),Pl=c.vec3();c.vec3();const Cl=c.mat4();class Ml{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=xl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=Bl;if(v){const e=wl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=j(f,t,Cl),_=Pl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fl=c.vec3(),El=c.vec3(),Il=c.vec3();c.vec3();const Dl=c.mat4();class Sl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Fl;if(A){const t=El;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,Dl),g=Il,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Tl=c.vec3(),Ll=c.vec3(),Rl=c.vec3();c.vec3();const Ul=c.mat4();class kl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Tl;if(g){const t=c.transformPoint3(u,A,Ll);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,Ul),f=Rl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ol=c.vec3(),Nl=c.vec3(),Ql=c.vec3();c.vec3();const Vl=c.mat4();class Hl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Ol;if(g){const t=Nl;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=j(d,e,Vl),f=Ql,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const jl=c.vec3(),Gl=c.vec3(),zl=c.vec3();c.vec3(),c.vec4();const Wl=c.mat4();class Kl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=jl;if(g){const t=c.transformPoint3(u,A,Gl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,Wl),f=zl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ya(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new hl(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new fl(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Kl(this._scene)),this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ml(this._scene)),this._snapRenderer||(this._snapRenderer=new yl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ga(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ga(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ya(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new kl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Hl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new tl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ol(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new hl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Kl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Kl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new fl(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ml(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sl(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Jl={};class Yl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Zl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const ql={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(ql,null,4));let e=0;Object.keys(ql).forEach((t=>{t.startsWith("size")&&(e+=ql[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/ql.totalPolygons).toFixed(2)}`);let t={};Object.keys(ql).forEach((i=>{i.startsWith("size")&&(t[i]=`${(ql[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class $l{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);ql.sizeDataColorsAndFlags+=h.byteLength,ql.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);ql.sizeDataTextureOffsets+=r.byteLength,ql.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);ql.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Yl,this._dtxState=new Zl,this._dtxTextureFactory=new $l,this._state=new tt({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&ql.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*tA||t+r>4096*tA)&&ql.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*tA&&t+r<=4096*tA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;ql.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;ql.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,ql.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||nA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,ql.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,ql.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,ql.totalPolygons32Bits+=t.numTriangles),ql.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,ql.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,ql.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,ql.totalEdges32Bits+=t.numEdges),ql.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,sA)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,sA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,sA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,rA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,iA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Hs.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Hs.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Hs.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Hs.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Hs.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Hs.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class lA{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 AA{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const hA={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 cA{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==pA[e])return void pA[e].push({onLoad:t,onProgress:i,onError:s});pA[e]=[],pA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=pA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{hA.add(e,t);const i=pA[e];delete pA[e];for(let e=0,s=i.length;e{const i=pA[e];if(void 0===i)throw this.manager.itemError(e),t;delete pA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class gA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let mA=0;class _A{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new gA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new fA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new fA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=_A.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(_A.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(_A.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(_A.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),mA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),mA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),mA--}}_A.BasisFormat={ETC1S:0,UASTC_4x4:1},_A.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},_A.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},_A.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete vA[t],i.destroy()}))),i} +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}let o=!0,n=o?Float64Array:Float32Array;const a=new n(3),l=new n(16),A=new n(16),h=new n(4),c={setDoublePrecisionEnabled(e){o=e,n=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new n(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>c.dotVec4(e,e),lenVec4:e=>Math.sqrt(c.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>c.dotVec3(e,e),sqLenVec2:e=>c.dotVec2(e,e),lenVec3:e=>Math.sqrt(c.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>c.lenVec3(c.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(c.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>c.lenVec2(c.subVec2(t,i,e))})(),rcpVec3:(e,t)=>c.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/c.lenVec4(e);return c.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/c.lenVec3(e);return c.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/c.lenVec2(e);return c.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=c.dotVec3(e,t)/Math.sqrt(c.sqLenVec3(e)*c.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=c.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=c.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=c.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||c.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>c.m4s(0),setMat4ToOnes:()=>c.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>c.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>c.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>c.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],x=t[3],B=t[4],w=t[5],P=t[6],C=t[7],M=t[8],F=t[9],E=t[10],I=t[11],D=t[12],S=t[13],T=t[14],L=t[15];return i[0]=v*s+b*a+y*c+x*f,i[1]=v*r+b*l+y*u+x*g,i[2]=v*o+b*A+y*d+x*m,i[3]=v*n+b*h+y*p+x*_,i[4]=B*s+w*a+P*c+C*f,i[5]=B*r+w*l+P*u+C*g,i[6]=B*o+w*A+P*d+C*m,i[7]=B*n+w*h+P*p+C*_,i[8]=M*s+F*a+E*c+I*f,i[9]=M*r+F*l+E*u+I*g,i[10]=M*o+F*A+E*d+I*m,i[11]=M*n+F*h+E*p+I*_,i[12]=D*s+S*a+T*c+L*f,i[13]=D*r+S*l+T*u+L*g,i[14]=D*o+S*A+T*d+L*m,i[15]=D*n+S*h+T*p+L*_,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=a*d+l*g+A*v,i[4]=a*p+l*m+A*b,i[7]=a*f+l*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=c.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,x=s*A-o*a,B=r*A-o*l,w=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,F=c*m-d*f,E=u*m-d*g,I=1/(_*E-v*F+b*M+y*C-x*P+B*w);return t[0]=(a*E-l*F+A*M)*I,t[1]=(-s*E+r*F-o*M)*I,t[2]=(f*B-g*x+m*y)*I,t[3]=(-c*B+u*x-d*y)*I,t[4]=(-n*E+l*C-A*P)*I,t[5]=(i*E-r*C+o*P)*I,t[6]=(-p*B+g*b-m*v)*I,t[7]=(h*B-u*b+d*v)*I,t[8]=(n*F-a*C+A*w)*I,t[9]=(-i*F+s*C-o*w)*I,t[10]=(p*x-f*b+m*_)*I,t[11]=(-h*x+c*b-d*_)*I,t[12]=(-n*M+a*P-l*w)*I,t[13]=(i*M-s*P+r*w)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||c.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||c.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.translationMat4v(e,r))})(),translationMat4s:(e,t)=>c.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>c.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=c.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,u,d,p,f,g;return h=a*l,u=l*A,d=A*a,p=a*r,f=l*r,g=A*r,(i=i||c.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*d-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*u+p,i[7]=0,i[8]=n*d+f,i[9]=n*u-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>c.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=c.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=c.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,c.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>c.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=c.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,u=s*l,d=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=u+v,i[2]=d-_,i[3]=0,i[4]=u-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=d+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=c.vec4()){const s=c.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],u=e[6],d=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,d),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(u,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,d),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(-h,d),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(u,d),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,d))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(u,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,d),i[1]=0)),i},composeMat4:(e,t,i,s=c.mat4())=>(c.quaternionToRotationMat4(t,s),c.scaleMat4v(i,s),c.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=c.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=c.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=c.lenVec3(e);c.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,u=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=u,t[9]*=u,t[10]*=u,c.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=c.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],u=t[1],d=t[2];if(r===h&&o===u&&n===d)return c.identityMat4();let p,f,g,m,_,v,b,y,x,B;return p=r-h,f=o-u,g=n-d,B=1/Math.sqrt(p*p+f*f+g*g),p*=B,f*=B,g*=B,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,B=Math.sqrt(m*m+_*_+v*v),B?(B=1/B,m*=B,_*=B,v*=B):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,x=p*_-f*m,B=Math.sqrt(b*b+y*y+x*x),B?(B=1/B,b*=B,y*=B,x*=B):(b=0,y=0,x=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=x,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+x*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>c.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=c.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];c.addVec4(r,s,l),c.subVec4(r,s,A);const o=2*s[2],n=A[0],a=A[1],h=A[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=l[0]/n,i[9]=l[1]/a,i[10]=-l[2]/h,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/h,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=c.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],c.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=c.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],x=e[13],B=e[14],w=e[15];let P;for(let e=0;e{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||c.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||c.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=c.vec4()){const s=e[0]*c.DEGTORAD/2,r=e[1]*c.DEGTORAD/2,o=e[2]*c.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),u=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"YXZ"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"ZXY"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l-A*h*u):"ZYX"===t?(i[0]=A*a*l-n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l+A*h*u):"YZX"===t?(i[0]=A*a*l+n*h*u,i[1]=n*h*l+A*a*u,i[2]=n*a*u-A*h*l,i[3]=n*a*l-A*h*u):"XZY"===t&&(i[0]=A*a*l-n*h*u,i[1]=n*h*l-A*a*u,i[2]=n*a*u+A*h*l,i[3]=n*a*l+A*h*u),i},mat4ToQuaternion(e,t=c.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let u;const d=i+n+h;return d>0?(u=.5/Math.sqrt(d+1),t[3]=.25/u,t[0]=(A-a)*u,t[1]=(r-l)*u,t[2]=(o-s)*u):i>n&&i>h?(u=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/u,t[0]=.25*u,t[1]=(s+o)/u,t[2]=(r+l)/u):n>h?(u=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/u,t[0]=(s+o)/u,t[1]=.25*u,t[2]=(a+A)/u):(u=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/u,t[0]=(r+l)/u,t[1]=(a+A)/u,t[2]=.25*u),t},vec3PairToQuaternion(e,t,i=c.vec4()){const s=Math.sqrt(c.dotVec3(e,e)*c.dotVec3(t,t));let r=s+c.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):c.cross3Vec3(e,t,i),i[3]=r,c.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=c.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||c.vec3(),c.quaternionToRotationMat4(t,e),c.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=c.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=c.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,u=A*r+l*s-n*o,d=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+u*-l-d*-a,i[1]=u*A+p*-a+d*-n-h*-l,i[2]=d*A+p*-l+h*-a-u*-n,i},quaternionToMat4(e,t){t=c.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,u=l*o,d=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+u,t[2]=f-h,t[4]=p-u,t[5]=1-(d+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(d+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=c.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>c.normalizeQuaternion(c.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=c.vec4()){const i=(e=c.normalizeQuaternion(e,h))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],x=e[14],B=e[15];for(s=0;s{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],c.subVec3(t,e,i),Math.abs(c.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=c.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],u=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>u?h:u,Math.abs(c.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||c.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||c.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=c.AABB3())=>(e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MAX_DOUBLE,e[3]=c.MIN_DOUBLE,e[4]=c.MIN_DOUBLE,e[5]=c.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=c.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new n(3);return(t,i,s)=>{i=i||c.AABB3();let r,o,n,a=c.MAX_DOUBLE,l=c.MAX_DOUBLE,A=c.MAX_DOUBLE,h=c.MIN_DOUBLE,u=c.MIN_DOUBLE,d=c.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>u&&(u=o),n>d&&(d=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=u,i[5]=d,i}})(),OBB3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=c.AABB3()){let i,s,r,o=c.MAX_DOUBLE,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE,h=c.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new n(3);return(t,i)=>{i=i||c.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=u);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new n(3),t=new n(3);return(i,s)=>{s=s||c.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;ru&&(u=h);return s[3]=u,s}})(),getSphere3Center:(e,t=c.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=c.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=c.MAX_DOUBLE,e[1]=c.MAX_DOUBLE,e[2]=c.MIN_DOUBLE,e[3]=c.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=c.AABB2()){let i,s,r,o,n=c.MAX_DOUBLE,a=c.MAX_DOUBLE,l=c.MIN_DOUBLE,A=c.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=c.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,u=n*a-r*A,d=r*l-o*a,p=Math.sqrt(h*h+u*u+d*d);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=u/p,s[2]=d/p),s},rayTriangleIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3);return(o,n,a,l,A,h)=>{h=h||c.vec3();const u=c.subVec3(l,a,e),d=c.subVec3(A,a,t),p=c.cross3Vec3(n,d,i),f=c.dotVec3(u,p);if(f<1e-6)return null;const g=c.subVec3(o,a,s),m=c.dotVec3(g,p);if(m<0||m>f)return null;const _=c.cross3Vec3(g,u,r),v=c.dotVec3(n,_);if(v<0||m+v>f)return null;const b=c.dotVec3(d,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new n(3),t=new n(3),i=new n(3),s=new n(3);return(r,o,n,a,l,A)=>{A=A||c.vec3(),o=c.normalizeVec3(o,e);const h=c.subVec3(a,n,t),u=c.subVec3(l,n,i),d=c.cross3Vec3(h,u,s);c.normalizeVec3(d,d);const p=-c.dotVec3(n,d),f=-(c.dotVec3(r,d)+p)/c.dotVec3(o,d);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r,o,n,a)=>{const l=c.subVec3(n,r,e),A=c.subVec3(o,r,t),h=c.subVec3(s,r,i),u=c.dotVec3(l,l),d=c.dotVec3(l,A),p=c.dotVec3(l,h),f=c.dotVec3(A,A),g=c.dotVec3(A,h),m=u*f-d*d;if(0===m)return null;const _=1/m,v=(f*p-d*g)*_,b=(u*g-d*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=c.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3);return(n,a,l)=>{let A,h;const u=new Array(n.length/3);let d,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new n(3),t=new n(3),i=new n(3),s=new n(3),r=new n(3),o=new n(3),a=new n(3);return(n,l,A)=>{const h=new Float32Array(n.length);for(let u=0;u>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,u;const d=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new n(4),t=new n(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,c.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],c.transformVec3(i,e,t),c.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new n(16),t=new n(16),i=new n(4),s=new n(4),r=new n(4),o=new n(4);return(n,a,l,A,h,u)=>{const d=c.mulMat4(l,a,e),p=c.inverseMat4(d,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,c.transformVec4(p,i,s),c.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,c.transformVec4(p,r,o),c.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],c.subVec3(o,s,u),c.normalizeVec3(u)}})(),canvasPosToLocalRay:(()=>{const e=new n(3),t=new n(3);return(i,s,r,o,n,a,l)=>{c.canvasPosToWorldRay(i,s,r,n,e,t),c.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new n(16),t=new n(4),i=new n(4);return(s,r,o,n,a)=>{const l=c.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],c.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new n(6),l={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let A,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;Aa[3]&&(a[3]=r[t]),r[t+1]a[4]&&(a[4]=r[t+1]),r[t+2]a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return l.triangles=i,l.leaf=!0,l;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),l.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};c.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[E.index1],L=i[E.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}(),c.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const p={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var f=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){M.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:m,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return _.isString(e)||_.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(_.isNumeric(e)||_.isString(e)?`${e}`:e.id)===(_.isNumeric(t)||_.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return _.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return _.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{b.removeItem(e.id),delete M.scenes[e.id],delete v[e.id],p.components.scenes--}))},this.clear=function(){let e;for(const t in M.scenes)M.scenes.hasOwnProperty(t)&&(e=M.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete M.scenes[e.id]))},this.scheduleTask=function(e,t=null){y.push(e),y.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;y.length>0&&(e<0||s0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}for(let e in M.scenes)M.scenes[e].compile();I(e),P=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{F()}),100);const E=function(){let e=Date.now();if(w=e-P,P>0&&w>0){var t=1e3/w;C+=t,B.push(t),B.length>=30&&(C-=B.shift()),p.frame.fps=Math.round(C/B.length)}I(e),function(e){for(var t in x.time=e,M.scenes)if(M.scenes.hasOwnProperty(t)){var i=M.scenes[t];x.sceneId=t,x.startTime=i.startTime,x.deltaTime=null!=x.prevTime?x.time-x.prevTime:0,i.fire("tick",x,!0)}x.prevTime=e}(e),function(){const e=M.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=v[n],s||(s=v[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(F):requestAnimationFrame(E)};function I(e){const t=M.runTasks(e+10),i=M.getNumTasks();p.frame.tasksRun=t,p.frame.tasksScheduled=i,p.frame.tasksBudget=10}E();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+_.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(_.isNumeric(i)||_.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+_.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+_.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+_.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():M.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){M.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class U{constructor(){this.planes=[new R,new R,new R,new R,new R,new R]}}function k(e,t,i){const s=c.mulMat4(i,t,L),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],u=s[7],d=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,u-l,g-d,b-m),e.planes[1].set(a+r,u+l,g+d,b+m),e.planes[2].set(a-o,u-A,g-p,b-_),e.planes[3].set(a+o,u+A,g+p,b+_),e.planes[4].set(a-n,u-h,g-f,b-v),e.planes[5].set(a+n,u+h,g+f,b+v)}function O(e,t){let i=U.INSIDE;const s=S,r=T;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return U.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=U.INTERSECT)}return i}U.INSIDE=0,U.INTERSECT=1,U.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=c.vec2(),this._canvasMarqueeCorner2=c.vec2(),this._canvasMarquee=c.AABB2(),this._marqueeFrustum=new U,this._marqueeFrustumProjMat=c.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=U.INTERSECT)=>{if(s===U.INTERSECT&&(s=O(this._marqueeFrustum,i.aabb)),s!==U.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,u=-(this._canvasMarquee[1]-r)*n+1,d=this.viewer.scene.camera.frustum.near*(17*a);c.frustumMat4(l,A,h*a,u*a,d,1e4,this._marqueeFrustumProjMat),k(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class Q{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}class V{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){M.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const H=c.vec3(),j=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,c.transformVec4(s,t,i),c.setMat4Translation(s,i,o),o.slice()}}();function G(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function z(e,t,i,s=1e3){const r=c.getPositionsCenter(e,H),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(c.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){oe.set(this._viewPos),oe[3]=1,c.transformPoint4(this.scene.camera.projMatrix,oe,ne);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ne[0]/ne[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ne[1]/ne[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof re?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),G(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const le={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class Ae{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class he{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ce{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(le.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var ue=c.vec3(),de=c.vec3();class pe extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originMarker=new ae(i,t.origin),this._cornerMarker=new ae(i,t.corner),this._targetMarker=new ae(i,t.target),this._originWorld=c.vec3(),this._cornerWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new Ae(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new Ae(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new ce(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const d=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>d||f>d||g>d)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,u=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&u(e.offsetParent)),d=c.vec2();this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,d),this.markerDiv.style.left=d[0]-5+"px",this.markerDiv.style.top=d[1]-5+"px"):(this.markerDiv.style.left=u(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class me extends ae{constructor(e,t){if(super(e,t),this.plugin=t.plugin,this._container=t.container,!this._container)throw"config missing: container";if(!t.markerElement&&!t.markerHTML)throw"config missing: need either markerElement or markerHTML";if(!t.labelElement&&!t.labelHTML)throw"config missing: need either labelElement or labelHTML";this._htmlDirty=!1,t.markerElement?(this._marker=t.markerElement,this._marker.addEventListener("click",this._onMouseClickedExternalMarker=()=>{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

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

";_.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const _e=c.vec3(),ve=c.vec3(),be=c.vec3();class ye extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const xe=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class Be extends D{constructor(e,t={}){super(e,t),this._backgroundColor=c.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new ye(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+c.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Pe.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Pe.FS_MAX_FLOAT_PRECISION="mediump":Pe.FS_MAX_FLOAT_PRECISION="lowp":Pe.FS_MAX_FLOAT_PRECISION="mediump",Pe.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Pe.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Pe.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Pe.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Pe.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Pe.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Pe.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Pe.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Pe.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Pe.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Pe.SUPPORTED_EXTENSIONS[e]=!0})))}class Me{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Fe{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Te(e){console.error(e.join("\n"))}class Le{constructor(e,t){this.id=De.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Fe(e,e.VERTEX_SHADER,Se(this.source.vertex)),this._fragmentShader=new Fe(e,e.FRAGMENT_SHADER,Se(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Te(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Te(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Te(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Te(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void Te(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ue{constructor(e,t){this.scene=e,this.aabb=c.AABB3(),this.origin=c.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Ue(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Ue(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new Le(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,u=this._getInverseProjectMat(),d=Math.random(),p="perspective"===s.camera.projection;Qe[0]=o,Qe[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,u),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Qe),t.uniform1f(this._uRandomSeed,d);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new Le(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Re(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Re(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Re(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const He=new Float32Array(Xe(17,[0,1])),je=new Float32Array(Xe(17,[1,0])),Ge=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(Ke(s,t));return i}(17,4)),ze=new Float32Array(2);class We{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new Le(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Re(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Re(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Re(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=c.mat4();return()=>(e&&c.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),ze[0]=n,ze[1]=a,s.uniform2fv(this._uViewport,ze),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,je):s.uniform2fv(this._uSampleOffsets,He),s.uniform1fv(this._uSampleWeights,Ge);const u=e.getDepthTexture(),d=t.getTexture();r.bindTexture(this._uDepthTexture,u,0),r.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function Ke(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function Xe(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class Je{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class Ye{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new Je(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function Ze(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const qe=function(t,i){i=i||{};const s=new we(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},u=[],d=[],f=!0,g=!0,m=!0,_=!0,v=!0,b=!0,y=!0,x=!0;const B=new Ye(t);let w=!1;const P=new Ve(t),C=new We(t);function M(){f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),f=!1,g=!0),g&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&(t.drawableListPreCull.sort(t.stateSortCompare),t.drawableList=t.drawableListPreCull)}let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),g=!1,m=!0),m&&function(){let e=0;for(let t=0,i=u.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||k>0||O>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||O>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),O>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=d.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let F=null,E=null,T=null,L=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),L=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;E=c.normalizeVec3([t[0]/c.MAX_INT,t[1]/c.MAX_INT,t[2]/c.MAX_INT]),F=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===y&&null==F)return null;let R=null;null!==F&&(R=t.camera.projectWorldPos(F));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===L,h.snappedToVertex="vertex"===L,h.worldPos=F,h.worldNormal=E,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=R||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ne(t,B),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const et=new e({});class tt{constructor(e){this.id=et.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){et.removeItem(this.id)}}class it extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new tt({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class st extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),c.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class rt extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),c.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ot extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){c.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class nt extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new tt({matrix:c.mat4(),inverseMatrix:c.mat4(),transposedMatrix:c.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(c.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(c.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,c.mulMat4v4(this.inverseMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,c.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const at=c.vec3(),lt=c.vec3(),At=c.vec3(),ht=c.vec3(),ct=c.vec3(),ut=c.vec3(),dt=c.vec4(),pt=c.vec4(),ft=c.vec4(),gt=c.mat4(),mt=c.mat4(),_t=c.vec3(),vt=c.vec3(),bt=c.vec3(),yt=c.vec3();class xt extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new tt({deviceMatrix:c.mat4(),hasDeviceMatrix:!1,matrix:c.mat4(),normalMatrix:c.mat4(),inverseMatrix:c.mat4()}),this._perspective=new st(this),this._ortho=new rt(this),this._frustum=new ot(this),this._customProjection=new nt(this),this._project=this._perspective,this._eye=c.vec3([0,0,10]),this._look=c.vec3([0,0,0]),this._up=c.vec3([0,1,0]),this._worldUp=c.vec3([0,1,0]),this._worldRight=c.vec3([1,0,0]),this._worldForward=c.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(c.subVec3(this._eye,this._look,_t),c.normalizeVec3(_t,vt),c.mulVec3Scalar(vt,1e3,bt),c.addVec3(this._look,bt,yt),t=yt):t=this._eye,e.hasDeviceMatrix?(c.lookAtMat4v(t,this._look,this._up,mt),c.mulMat4(e.deviceMatrix,mt,e.matrix)):c.lookAtMat4v(t,this._look,this._up,e.matrix),c.inverseMat4(this._state.matrix,this._state.inverseMatrix),c.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=c.subVec3(this._eye,this._look,at);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,gt),t=c.transformPoint3(gt,t,lt),this.eye=c.addVec3(this._look,t,At),this.up=c.transformPoint3(gt,this._up,ht)}orbitPitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._eye,this._look,at);const i=c.cross3Vec3(c.normalizeVec3(t,lt),c.normalizeVec3(this._up,At));c.rotationMat4v(.0174532925*e,i,gt),t=c.transformPoint3(gt,t,ht),this.up=c.transformPoint3(gt,this._up,ct),this.eye=c.addVec3(t,this._look,ut)}yaw(e){let t=c.subVec3(this._look,this._eye,at);c.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,gt),t=c.transformPoint3(gt,t,lt),this.look=c.addVec3(t,this._eye,At),this._gimbalLock&&(this.up=c.transformPoint3(gt,this._up,ht))}pitch(e){if(this._constrainPitch&&(e=c.dotVec3(this._up,this._worldUp)/c.DEGTORAD)<1)return;let t=c.subVec3(this._look,this._eye,at);const i=c.cross3Vec3(c.normalizeVec3(t,lt),c.normalizeVec3(this._up,At));c.rotationMat4v(.0174532925*e,i,gt),this.up=c.transformPoint3(gt,this._up,ut),t=c.transformPoint3(gt,t,ht),this.look=c.addVec3(t,this._eye,ct)}pan(e){const t=c.subVec3(this._eye,this._look,at),i=[0,0,0];let s;if(0!==e[0]){const r=c.cross3Vec3(c.normalizeVec3(t,[]),c.normalizeVec3(this._up,lt));s=c.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=c.mulVec3Scalar(c.normalizeVec3(this._up,At),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=c.mulVec3Scalar(c.normalizeVec3(t,ht),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=c.addVec3(this._eye,i,ct),this.look=c.addVec3(this._look,i,ut)}zoom(e){const t=c.subVec3(this._eye,this._look,at),i=Math.abs(c.lenVec3(t,lt)),s=Math.abs(i+e);if(s<.5)return;const r=c.normalizeVec3(t,At);this.eye=c.addVec3(this._look,c.mulVec3Scalar(r,s),ht)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=c.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return c.lenVec3(c.subVec3(this._look,this._eye,at))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=dt,i=pt,s=ft;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,c.mulMat4v4(this.viewMatrix,t,i),c.mulMat4v4(this.projMatrix,i,s),c.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Bt extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class wt extends Bt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new tt({type:"dir",dir:c.vec3([1,1,1]),color:c.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=c.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];c.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=c.identityMat4()),c.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Je(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Pt extends Bt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:c.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Ct extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),p.memory.meshes++}destroy(){super.destroy(),p.memory.meshes--}}var Mt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;ux)||(T=i[E.index1],L=i[E.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}();const Ft=function(){const e=c.mat4(),t=c.mat4();return function(i,s){s=s||c.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return c.identityMat4(e),c.translationMat4v(i,e),c.identityMat4(t),c.scalingMat4v([a/h,l/h,A/h],t),c.mulMat4(e,t,s),s}}();var Et=function(){const e=c.mat4(),t=c.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function St(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Tt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Lt={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Dt(e,a,"floor","ceil"),s=St(i),o=Tt(e,a,s),o>n&&(r=i,n=o),i=Dt(e,a,"ceil","ceil"),s=St(i),o=Tt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},Rt=p.memory,Ut=c.AABB3();class kt extends Ct{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new tt({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Lt.getPositionsBounds(t.positions),s=Lt.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Lt.getUVBounds(t.uv),s=Lt.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Lt.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),Rt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Rt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Re(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Rt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new Re(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Rt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Re(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Rt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Re(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Rt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Mt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Rt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=c.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Re(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Rt.positions+=this._pickTrianglePositionsBuf.numItems,Rt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Lt.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Lt.getPositionsBounds(e),s=Lt.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Lt.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Lt.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=c.AABB3()),c.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=c.OBB3()),c.positions3ToAABB3(this._state.positions,Ut,this._state.positionsDecodeMatrix),c.AABB3ToOBB3(Ut,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Rt.meshes--}}function Ot(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Nt extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),p.memory.materials++}destroy(){super.destroy(),p.memory.materials--}}const Qt={opaque:0,mask:1,blend:2},Vt=["opaque","mask","blend"];class Ht extends Nt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new tt({type:"PhongMaterial",ambient:c.vec3([1,1,1]),diffuse:c.vec3([1,1,1]),specular:c.vec3([1,1,1]),emissive:c.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Qt[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 Vt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const jt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class Gt extends Nt{get type(){return"EmphasisMaterial"}get presets(){return jt}constructor(e,t={}){super(e,t),this._state=new tt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=jt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(jt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const zt={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class Wt extends Nt{get type(){return"EdgeMaterial"}get presets(){return zt}constructor(e,t={}){super(e,t),this._state=new tt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=zt[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(zt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const Kt={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class Xt extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=c.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return Kt}set units(e){e||(e="meters");Kt[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=c.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=c.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class Jt extends D{constructor(e,t={}){super(e,t),this._supported=Pe.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class Yt extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const Zt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class qt extends Nt{get type(){return"PointsMaterial"}get presets(){return Zt}constructor(e,t={}){super(e,t),this._state=new tt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=Zt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Zt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const $t={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ei extends Nt{get type(){return"LinesMaterial"}get presets(){return $t}constructor(e,t={}){super(e,t),this._state=new tt({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=$t[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys($t).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function ti(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new qe(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=c.vec4([0,0,0,0]),t=c.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+_.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=c.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],_.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&M.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;if((e.snapToVertex||e.snapToEdge)&&!e.canvasPos)return void this.error("Scene.snapPick() `canvasPos` parameter expected for `snapToVertex:true` or `snapToEdge:true`");(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=ti(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ti(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=c.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){_.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const si=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=ni(e),u=s.getNumAllocatedSectionPlanes()>0,d=oi(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=ni(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=oi(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+ri[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+ri[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ri[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ri[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ri[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ri[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class ci{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const ui=new e({}),di=c.vec3(),pi=function(e,t){this.id=ui.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ci(t),this._allocate(t)},fi={};pi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=fi[t];return i||(i=new pi(t,e),fi[t]=i,p.memory.programs++),i._useCount++,i},pi.prototype.put=function(){0==--this._useCount&&(ui.removeItem(this.id),this._program&&this._program.destroy(),delete fi[this._hash],p.memory.programs--)},pi.prototype.webglContextRestored=function(){this._program=null},pi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const mi=new e({}),_i=c.vec3(),vi=function(e,t){this.id=mi.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new gi(t),this._allocate(t)},bi={};vi.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=bi[t];return i||(i=new vi(t,e),bi[t]=i,p.memory.programs++),i._useCount++,i},vi.prototype.put=function(){0==--this._useCount&&(mi.removeItem(this.id),this._program&&this._program.destroy(),delete bi[this._hash],p.memory.programs--)},vi.prototype.webglContextRestored=function(){this._program=null},vi.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const xi=c.vec3(),Bi=function(e,t){this._hash=e,this._shaderSource=new yi(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},wi={};Bi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=wi[t];if(!i){if(i=new Bi(t,e),i.errors)return console.log(i.errors.join("\n")),null;wi[t]=i,p.memory.programs++}return i._useCount++,i},Bi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete wi[this._hash],p.memory.programs--)},Bi.prototype.webglContextRestored=function(){this._program=null},Bi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},Bi.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Le(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Ci=c.vec3(),Mi=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Pi(t),this._allocate(t)},Fi={};Mi.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Fi[t];if(!i){if(i=new Mi(t,e),i.errors)return console.log(i.errors.join("\n")),null;Fi[t]=i,p.memory.programs++}return i._useCount++,i},Mi.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Fi[this._hash],p.memory.programs--)},Mi.prototype.webglContextRestored=function(){this._program=null},Mi.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const Ii=c.vec3(),Di=function(e,t){this._hash=e,this._shaderSource=new Ei(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Si={};Di.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=Si[t];if(!i){if(i=new Di(t,e),i.errors)return console.log(i.errors.join("\n")),null;Si[t]=i,p.memory.programs++}return i._useCount++,i},Di.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Si[this._hash],p.memory.programs--)},Di.prototype.webglContextRestored=function(){this._program=null},Di.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Li=function(e,t){this._hash=e,this._shaderSource=new Ti(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ri={};Li.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Ri[i];if(!s){if(s=new Li(i,e),s.errors)return console.log(s.errors.join("\n")),null;Ri[i]=s,p.memory.programs++}return s._useCount++,s},Li.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ri[this._hash],p.memory.programs--)},Li.prototype.webglContextRestored=function(){this._program=null},Li.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Li.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new Le(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Xi=function(){const e=c.vec3(),t=c.vec3(),i=c.vec3(),s=c.vec3(),r=c.vec3(),o=c.vec3(),n=c.vec4(),a=c.vec3(),l=c.vec3(),A=c.vec3(),h=c.vec3(),u=c.vec3(),d=c.vec3(),p=c.vec3(),f=c.vec3(),g=c.vec3(),m=c.vec4(),_=c.vec4(),v=c.vec4(),b=c.vec3(),y=c.vec3(),x=c.vec3(),B=c.vec3(),w=c.vec3(),P=c.vec3(),C=c.vec3(),M=c.vec3(),F=c.vec3(),E=c.vec3(),I=c.vec3();return function(D,S,T,L){var R=L.primIndex;if(null!=R&&R>-1){const N=D.geometry._state,Q=D.scene,V=Q.camera,H=Q.canvas;if("triangles"===N.primitiveName){L.primitive="triangle";const Q=R,G=N.indices,z=N.positions;let W,K,X;if(G){var U=G[Q+0],k=G[Q+1],O=G[Q+2];o[0]=U,o[1]=k,o[2]=O,L.indices=o,W=3*U,K=3*k,X=3*O}else W=3*Q,K=W+3,X=K+3;if(i[0]=z[W+0],i[1]=z[W+1],i[2]=z[W+2],s[0]=z[K+0],s[1]=z[K+1],s[2]=z[K+2],r[0]=z[X+0],r[1]=z[X+1],r[2]=z[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Lt.decompressPosition(i,e,i),Lt.decompressPosition(s,e,s),Lt.decompressPosition(r,e,r))}L.canvasPos?c.canvasPosToLocalRay(H.canvas,D.origin?j(S,D.origin):S,T,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&c.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),c.normalizeVec3(t),c.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,c.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,c.transformVec4(V.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,c.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const J=N.normals;if(J){if(N.compressGeometry){const e=3*U,t=3*k,i=3*O;Lt.decompressNormal(J.subarray(e,e+2),h),Lt.decompressNormal(J.subarray(t,t+2),u),Lt.decompressNormal(J.subarray(i,i+2),d)}else h[0]=J[W],h[1]=J[W+1],h[2]=J[W+2],u[0]=J[K],u[1]=J[K+1],u[2]=J[K+2],d[0]=J[X],d[1]=J[X+1],d[2]=J[X+2];const e=c.addVec3(c.addVec3(c.mulVec3Scalar(h,A[0],b),c.mulVec3Scalar(u,A[1],y),x),c.mulVec3Scalar(d,A[2],B),w);L.worldNormal=c.normalizeVec3(c.transformVec3(D.worldNormalMatrix,e,P))}const Y=N.uv;if(Y){if(p[0]=Y[2*U],p[1]=Y[2*U+1],f[0]=Y[2*k],f[1]=Y[2*k+1],g[0]=Y[2*O],g[1]=Y[2*O+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Lt.decompressUV(p,e,p),Lt.decompressUV(f,e,f),Lt.decompressUV(g,e,g))}L.uv=c.addVec3(c.addVec3(c.mulVec2Scalar(p,A[0],C),c.mulVec2Scalar(f,A[1],M),F),c.mulVec2Scalar(g,A[2],E),I)}}}}}();function Ji(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],v=[],b=[];let y,x,B,w,P,C,M,F,E,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(P=t-y*f,C=c-y*u,x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),m.push(P*B),m.push(S),m.push(P*w),v.push(x*p),v.push(1*y/o),g.push(P*B+l),g.push(C+A),g.push(P*w+h);for(y=0;y0){for(E=g.length/3,m.push(0),m.push(1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(t*B),m.push(1),m.push(t*w),v.push(I),v.push(D),g.push(t*B+l),g.push(c+A),g.push(t*w+h);for(x=0;x0){for(E=g.length/3,m.push(0),m.push(-1),m.push(0),v.push(.5),v.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),x=0;x<=r;x++)B=Math.sin(x*d),w=Math.cos(x*d),I=.5*Math.sin(x*d)+.5,D=.5*Math.cos(x*d)+.5,m.push(i*B),m.push(-1),m.push(i*w),v.push(I),v.push(D),g.push(i*B+l),g.push(0-c+A),g.push(i*w+h);for(x=0;x":{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 qi(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;_.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,v=(l||"").split("\n"),b=0,y=0,x=.04,B=0;B0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=ms(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=ms(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ms(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ys(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ys(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ms(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ms(i,this.magFilter)));const a=ms(i,this.format,this.encoding),l=ms(i,this.type),A=bs(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Ps extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new tt({texture:new vs({gl:this.scene.canvas.gl}),matrix:c.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=c.vec2([0,0]),this._scale=c.vec2([1,1]),this._rotate=c.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),p.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new vs({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=c.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=c.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?c.mulMat4(t,i):i),0!==this._rotate&&(i=c.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?c.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=xs(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=xs(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),p.memory.textures--}}const Cs=p.memory,Ms=c.AABB3();class Fs extends Ct{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new tt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=c.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Lt.getPositionsBounds(t.positions),o=Lt.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new Re(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Cs.positions+=i.positionsBuf.numItems,c.positions3ToAABB3(t.positions,this._aabb),c.positions3ToAABB3(r,Ms,i.positionsDecodeMatrix),c.AABB3ToOBB3(Ms,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new Re(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Cs.colors+=i.colorsBuf.numItems}if(t.uv){const e=Lt.getUVBounds(t.uv),r=Lt.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new Re(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Cs.uvs+=i.uvBuf.numItems}if(t.normals){const e=Lt.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new Re(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Cs.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Cs.indices+=i.indicesBuf.numItems;const o=Mt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Cs.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(),Cs.meshes--}}var Es={};function Is(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return _.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Ds(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return _.apply(e,{primitive:"lines",positions:o,indices:n})}function Ss(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),v=new Float32Array(d*p*3),b=new Float32Array(d*p*2);let y,x,B,w,P,C,M,F=0,E=0;for(y=0;y65535?Uint32Array:Uint16Array)(c*u*6);for(y=0;y360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],u=[],d=[],p=[];let f,g,m,v,b,y,x,B,w,P,C,M;for(B=0;B<=r;B++)for(x=0;x<=s;x++)f=x/s*o,g=.785398+B/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),v=(t+i*Math.cos(g))*Math.sin(f),b=i*Math.sin(g),h.push(m+a),h.push(v+l),h.push(b+A),d.push(1-x/s),d.push(B/r),y=c.normalizeVec3(c.subVec3([m,v,b],[a,l,A],[]),[]),u.push(y[0]),u.push(y[1]),u.push(y[2]);for(B=1;B<=r;B++)for(x=1;x<=s;x++)w=(s+1)*B+x-1,P=(s+1)*(B-1)+x-1,C=(s+1)*(B-1)+x,M=(s+1)*B+x,p.push(w),p.push(P),p.push(C),p.push(C),p.push(M),p.push(w);return _.apply(e,{positions:h,normals:u,uv:d,indices:p})}function Ls(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e>8},Es.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Es.parse={},Es.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Rs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=c.vec3(t.pos||[0,0,0]),this._up=c.vec3(t.up||[0,1,0]),this._normal=c.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=c.vec3(),this._rtcPos=c.vec3(),this._imageSize=c.vec2(),this._texture=new Ps(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new As(this,{matrix:c.inverseMat4(c.lookAtMat4v(this._pos,c.subVec3(this._pos,this._normal,c.mat4()),this._up,c.mat4())),children:[this._bitmapMesh=new Ki(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new kt(this,Ss({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ht(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const Us=c.OBB3(),ks=c.OBB3(),Os=c.OBB3();class Ns{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=c.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(c.AABB3ToOBB3(this._aabbLocal,Us),this.transform?(c.transformOBB3(this.transform.worldMatrix,Us,ks),c.transformOBB3(this.model.worldMatrix,ks,Os),c.OBB3ToAABB3(Os,this._aabbWorld)):(c.transformOBB3(this.model.worldMatrix,Us,ks),c.OBB3ToAABB3(ks,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const Qs=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 Vs=0;const Hs={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},js=new Float32Array([1,1,1,1]),Gs=new Float32Array([0,0,0,1]),zs=c.vec4(),Ws=c.vec3(),Ks=c.vec3(),Xs=c.mat4();class Js{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;zs[0]=i,zs[1]=s,zs[2]=t.blendCutoff,zs[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,zs),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===Hs[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?Gs:js)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,p.memory.programs--}}class Ys extends Js{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Zs extends Ys{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class qs extends Ys{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class er extends Ys{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class tr extends er{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class ir extends er{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class sr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class rr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class or extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class nr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class ar extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class lr extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Ar extends Ys{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class hr extends Ys{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class ur extends Ys{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vr=c.vec3(),br=c.vec3(),yr=c.vec3(),xr=c.vec3(),Br=c.mat4();class wr extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=vr;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=br;if(l){const e=yr;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,Br),m=xr,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Pr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new $s(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new sr(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new rr(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new _r(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new wr(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Zs(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Zs(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new qs(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new qs(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new ur(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new ur(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new hr(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new hr(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new $s(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ar(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new lr(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new tr(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ir(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new sr(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new or(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cr(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new rr(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nr(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Ar(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new wr(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new _r(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Cr={};let Mr=65536,Fr=5e6;class Er{constructor(){}set doublePrecisionEnabled(e){c.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return c.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Mr=e}get maxDataTextureHeight(){return Mr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Fr=e}get maxGeometryBatchSize(){return Fr}}const Ir=new Er;class Dr{constructor(){this.maxVerts=Ir.maxGeometryBatchSize,this.maxIndices=3*Ir.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Sr=c.mat4(),Tr=c.mat4();function Lr(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,u=65525,d=u/l,p=u/A,f=u/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function kr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Or=c.mat4(),Nr=c.mat4(),Qr=c.vec4([0,0,0,1]),Vr=c.vec3(),Hr=c.vec3(),jr=c.vec3(),Gr=c.vec3(),zr=c.vec3(),Wr=c.vec3(),Kr=c.vec3();class Xr{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Cr[t];return i||(i=new Pr(e),Cr[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Cr[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Dr(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({origin:c.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=c.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=c.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=Or;m?c.inverseMat4(c.transposeMat4(m,Nr),e):c.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,u,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(u=0;uh&&(l=n,h=A),n=Ur(p,"floor","ceil"),a=kr(n),A=o(p,a),A>h&&(l=n,h=A),n=Ur(p,"ceil","ceil"),a=kr(n),A=o(p,a),A>h&&(l=n,h=A),s[r+u+0]=l[0],s[r+u+1]=l[1],s[r+u+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):Lr(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=c.mat4());if(e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new Re(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new Re(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Lt.getUVBounds(i.uv),r=Lt.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=c.mat3(r.decodeMatrix),e.uvBuf=new Re(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new Re(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&c.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Jr extends Js{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Yr extends Jr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Zr extends Jr{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class $r extends Jr{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class eo extends $r{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class to extends $r{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class io extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class so extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ro extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class oo extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class no extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class ao extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class lo extends Jr{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Ao={3e3:"linearToLinear",3001:"sRGBToLinear"};class ho extends Jr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Ao[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Ao[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),s.push("}"),s}}class uo extends Jr{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const bo=c.vec3(),yo=c.vec3(),xo=c.vec3(),Bo=c.vec3(),wo=c.mat4();class Po extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=bo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=yo;if(l){const e=c.transformPoint3(h,l,xo);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,wo),m=Bo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Co{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new io(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new so(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new vo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Po(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yr(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Yr(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Zr(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Zr(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new ho(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ho(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new uo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new uo(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new no(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ao(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new eo(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new to(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new io(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new ro(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new co(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new so(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new oo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new lo(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new vo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Po(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Mo={};const Fo=new Uint8Array(4),Eo=new Float32Array(1),Io=c.vec4([0,0,0,1]),Do=new Float32Array(3),So=c.vec3(),To=c.vec3(),Lo=c.vec3(),Ro=c.vec3(),Uo=c.vec3(),ko=c.vec3(),Oo=c.vec3(),No=new Float32Array(4);class Qo{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Mo[t];return i||(i=new Co(e),Mo[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Mo[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({numInstances:0,obb:c.OBB3(),origin:c.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new Re(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new Re(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new Re(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new Re(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=c.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new Re(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Re(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Re(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new Re(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new Re(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Fo[0]=t[0],Fo[1]=t[1],Fo[2]=t[2],Fo[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Fo,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?1:0)<<16,Eo[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(Eo,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Do[0]=t[0],Do[1]=t[1],Do[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Do,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],u=Io,d=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&c.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(c.transformVec3(a.normalMatrix,r,r),c.transformVec3(this.model.worldNormalMatrix,r,r),c.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class Vo extends Js{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class Ho extends Vo{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class jo extends Vo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Go=c.vec3(),zo=c.vec3(),Wo=c.vec3(),Ko=c.vec3(),Xo=c.mat4();class Jo extends Js{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Go;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=zo;if(l){const e=Wo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,Xo),m=Ko,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yo=c.vec3(),Zo=c.vec3(),qo=c.vec3(),$o=c.vec3(),en=c.mat4();class tn extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Yo;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Zo;if(l){const e=qo;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,en),m=$o,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class sn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ho(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new jo(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Jo(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new tn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const rn={};class on{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class nn{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=rn[t];return i||(i=new sn(e),rn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete rn[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new on(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Lr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new Re(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class An extends an{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const hn=c.vec3(),cn=c.vec3(),un=c.vec3();c.vec3();const dn=c.mat4();class pn extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=hn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=cn;if(l){const e=c.transformPoint3(h,l,un);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,dn),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const fn=c.vec3(),gn=c.vec3(),mn=c.vec3();c.vec3();const _n=c.mat4();class vn extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=fn;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=gn;if(l){const e=c.transformPoint3(h,l,mn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,_n),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class bn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new pn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new vn(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ln(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new An(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new pn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new vn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const yn={};const xn=new Uint8Array(4),Bn=new Float32Array(1),wn=new Float32Array(3),Pn=new Float32Array(4);class Cn{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=yn[t];return i||(i=new bn(e),yn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete yn[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({obb:c.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=c.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new Re(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new Re(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new Re(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=c.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Re(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";xn[0]=t[0],xn[1]=t[1],xn[2]=t[2],xn[3]=t[3],this._state.colorsBuf.setData(xn,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?255:0)<<16,Bn[0]=d,this._state.flagsBuf.setData(Bn,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(wn[0]=t[0],wn[1]=t[1],wn[2]=t[2],this._state.offsetsBuf.setData(wn,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Pn[0]=t[0],Pn[1]=t[4],Pn[2]=t[8],Pn[3]=t[12],this._state.modelMatrixCol0Buf.setData(Pn,i),Pn[0]=t[1],Pn[1]=t[5],Pn[2]=t[9],Pn[3]=t[13],this._state.modelMatrixCol1Buf.setData(Pn,i),Pn[0]=t[2],Pn[1]=t[6],Pn[2]=t[10],Pn[3]=t[14],this._state.modelMatrixCol2Buf.setData(Pn,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class Mn extends Js{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class Fn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class En extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class In extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class Dn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Sn extends Mn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const Tn=c.vec3(),Ln=c.vec3(),Rn=c.vec3(),Un=c.vec3(),kn=c.mat4();class On extends Js{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Tn;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ln;if(l){const e=Rn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,kn),m=Un,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Nn=c.vec3(),Qn=c.vec3(),Vn=c.vec3(),Hn=c.vec3(),jn=c.mat4();class Gn extends Js{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Nn;let g,m;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Qn;if(l){const e=Vn;c.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,jn),m=Hn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zn{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Fn(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new In(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Dn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sn(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new On(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Gn(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Wn={};class Kn{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class Xn{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Wn[t];return i||(i=new zn(e),Wn[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Wn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new Kn(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new tt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:c.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=c.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=c.vec3(e.origin))}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=Lr(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Re(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new Re(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new Re(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new Re(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Zn extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class qn extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class $n extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class ea extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class ta extends Jn{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class ia extends Jn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const sa=c.vec3(),ra=c.vec3(),oa=c.vec3();c.vec3();const na=c.mat4();class aa extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=sa;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ra;if(l){const e=c.transformPoint3(h,l,oa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,na),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const la=c.vec3(),Aa=c.vec3(),ha=c.vec3();c.vec3();const ca=c.mat4();class ua extends Js{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=la;let g;if(f[0]=c.safeInv(d[3]-d[0])*c.MAX_INT,f[1]=c.safeInv(d[4]-d[1])*c.MAX_INT,f[2]=c.safeInv(d[5]-d[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(f[0]),e.snapPickCoordinateScale[1]=c.safeInv(f[1]),e.snapPickCoordinateScale[2]=c.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Aa;if(l){const e=c.transformPoint3(h,l,ha);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=j(p,t,ca),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(u,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class da{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Yn(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Zn(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ta(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new qn(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $n(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ea(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ia(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new aa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ua(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const pa={};const fa=new Uint8Array(4),ga=new Float32Array(1),ma=new Float32Array(3),_a=new Float32Array(4);class va{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=pa[t];return i||(i=new da(e),pa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete pa[t],i._destroy()}))),i}(e.model.scene),this._aabb=c.collapseAABB3(),this._state=new tt({obb:c.OBB3(),numInstances:0,origin:e.origin?c.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new Re(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=c.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new Re(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new Re(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new Re(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";fa[0]=t[0],fa[1]=t[1],fa[2]=t[2],this._state.colorsBuf.setData(fa,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&K),r=!!(t&q),o=!!(t&$),n=!!(t&ee),a=!!(t&te),l=!!(t&J),A=!!(t&X);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?Hs.NOT_RENDERED:i?Hs.COLOR_TRANSPARENT:Hs.COLOR_OPAQUE,c=!s||A?Hs.NOT_RENDERED:n?Hs.SILHOUETTE_SELECTED:o?Hs.SILHOUETTE_HIGHLIGHTED:r?Hs.SILHOUETTE_XRAYED:Hs.NOT_RENDERED;let u=0;u=!s||A?Hs.NOT_RENDERED:n?Hs.EDGES_SELECTED:o?Hs.EDGES_HIGHLIGHTED:r?Hs.EDGES_XRAYED:a?i?Hs.EDGES_COLOR_TRANSPARENT:Hs.EDGES_COLOR_OPAQUE:Hs.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?Hs.PICK:Hs.NOT_RENDERED)<<12,d|=(t&Y?255:0)<<16,ga[0]=d,this._state.flagsBuf.setData(ga,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(ma[0]=t[0],ma[1]=t[1],ma[2]=t[2],this._state.offsetsBuf.setData(ma,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;_a[0]=t[0],_a[1]=t[4],_a[2]=t[8],_a[3]=t[12],this._state.modelMatrixCol0Buf.setData(_a,i),_a[0]=t[1],_a[1]=t[5],_a[2]=t[9],_a[3]=t[13],this._state.modelMatrixCol1Buf.setData(_a,i),_a[0]=t[2],_a[1]=t[6],_a[2]=t[10],_a[3]=t[14],this._state.modelMatrixCol2Buf.setData(_a,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Hs.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Hs.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const ba=c.vec3(),ya=c.vec3(),xa=c.mat4();class Ba{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ba;if(g){const t=c.transformPoint3(u,A,ya);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,xa)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class wa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ba(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const Pa={};class Ca{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class Ma{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class Fa{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const Ea={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ea,null,4));let e=0;Object.keys(Ea).forEach((t=>{t.startsWith("size")&&(e+=Ea[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ea.totalLines).toFixed(2)}`);let t={};Object.keys(Ea).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ea[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Ia{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);Ea.sizeDataColorsAndFlags+=l.byteLength,Ea.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ea.sizeDataTextureOffsets+=r.byteLength,Ea.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ea.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Pa[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Ca,this._dataTextureState=new Ma,this._dataTextureGenerator=new Ia,this._state=new tt({origin:c.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ea.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*Sa||t+r>4096*Sa)&&Ea.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Sa&&t+r<=4096*Sa}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;Ea.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,Ea.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||ka),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,Ea.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,Ea.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,Ea.totalLines32Bits+=t.numLines),Ea.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,La))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,La))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,La))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Ra))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ta))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const Na=c.vec3(),Qa=c.vec3(),Va=c.vec3();c.vec3();const Ha=c.vec4(),ja=c.mat4();class Ga{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Na;if(g){const t=c.transformPoint3(u,A,Qa);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,ja),f=Va,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new Le(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const za=new Float32Array([1,1,1]),Wa=c.vec3(),Ka=c.vec3(),Xa=c.vec3();c.vec3();const Ja=c.mat4();class Ya{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Wa;if(A){const t=Ka;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,Ja),g=Xa,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===Hs.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,za);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Za=new Float32Array([0,0,0,1]),qa=c.vec3(),$a=c.vec3();c.vec3();const el=c.mat4();class tl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=qa;if(g){const t=c.transformPoint3(u,A,$a);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,el)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===Hs.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===Hs.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,Za);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const il=c.vec3(),sl=c.vec3(),rl=c.mat4();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,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=il;if(g){const t=c.transformPoint3(u,A,sl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,rl)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const nl=c.vec3(),al=c.vec3(),ll=c.vec3(),Al=c.mat4();class hl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=nl;if(g){const t=c.transformPoint3(u,A,al);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(o.viewMatrix,e,Al),f=ll,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const cl=c.vec3(),ul=c.vec3(),dl=c.vec3();c.vec3();const pl=c.mat4();class fl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=cl;if(A){const e=ul;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=j(p,t,pl),g=dl,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gl=c.vec3(),ml=c.vec3(),_l=c.vec3(),vl=c.vec3();c.vec3();const bl=c.mat4();class yl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=gl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ml;if(v){const e=c.transformPoint3(u,A,_l);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=j(f,t,bl),_=vl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(B,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(B,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(B,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xl=c.vec3(),Bl=c.vec3(),wl=c.vec3(),Pl=c.vec3();c.vec3();const Cl=c.mat4();class Ml{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=xl;let m,_;g[0]=c.safeInv(p[3]-p[0])*c.MAX_INT,g[1]=c.safeInv(p[4]-p[1])*c.MAX_INT,g[2]=c.safeInv(p[5]-p[2])*c.MAX_INT,e.snapPickCoordinateScale[0]=c.safeInv(g[0]),e.snapPickCoordinateScale[1]=c.safeInv(g[1]),e.snapPickCoordinateScale[2]=c.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=Bl;if(v){const e=wl;c.transformPoint3(u,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=j(f,t,Cl),_=Pl,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),x=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*x,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Fl=c.vec3(),El=c.vec3(),Il=c.vec3();c.vec3();const Dl=c.mat4();class Sl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=Fl;if(A){const t=El;c.transformPoint3(u,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=j(p,e,Dl),g=Il,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Tl=c.vec3(),Ll=c.vec3(),Rl=c.vec3();c.vec3();const Ul=c.mat4();class kl{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Tl;if(g){const t=c.transformPoint3(u,A,Ll);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,Ul),f=Rl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ol=c.vec3(),Nl=c.vec3(),Ql=c.vec3();c.vec3();const Vl=c.mat4();class Hl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:u}=s,d=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=Ol;if(g){const t=Nl;c.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=j(d,e,Vl),f=Ql,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=d,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Pe.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const jl=c.vec3(),Gl=c.vec3(),zl=c.vec3();c.vec3(),c.vec4();const Wl=c.mat4();class Kl{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:u,rotationMatrixConjugate:d}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=jl;if(g){const t=c.transformPoint3(u,A,Gl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=j(r.viewMatrix,e,Wl),f=zl,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,d),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new Le(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${c.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Ya(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new hl(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new fl(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new Kl(this._scene)),this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ml(this._scene)),this._snapRenderer||(this._snapRenderer=new yl(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ga(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Ga(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ya(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new kl(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Hl(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new tl(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ol(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new hl(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Kl(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Kl(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new fl(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ml(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Sl(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Jl={};class Yl{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Zl{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const ql={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(ql,null,4));let e=0;Object.keys(ql).forEach((t=>{t.startsWith("size")&&(e+=ql[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/ql.totalPolygons).toFixed(2)}`);let t={};Object.keys(ql).forEach((i=>{i.startsWith("size")&&(t[i]=`${(ql[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class $l{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);ql.sizeDataColorsAndFlags+=h.byteLength,ql.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);ql.sizeDataTextureOffsets+=r.byteLength,ql.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Fa(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);ql.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete Jl[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Yl,this._dtxState=new Zl,this._dtxTextureFactory=new $l,this._state=new tt({origin:c.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=c.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){c.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&ql.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*tA||t+r>4096*tA)&&ql.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*tA&&t+r<=4096*tA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;ql.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;ql.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,ql.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||nA),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,ql.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,ql.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,ql.totalPolygons32Bits+=t.numTriangles),ql.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,ql.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,ql.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,ql.totalEdges32Bits+=t.numEdges),ql.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&K&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&$&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&q&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&ee&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&Y&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&te&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&J&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&X&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&K?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&te?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&Y?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&X?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&J?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,sA)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,sA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,sA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,rA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,iA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,Hs.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,Hs.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,Hs.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Hs.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,Hs.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,Hs.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,Hs.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,Hs.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,Hs.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,Hs.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,Hs.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,Hs.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class lA{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 AA{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const hA={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 cA{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==pA[e])return void pA[e].push({onLoad:t,onProgress:i,onError:s});pA[e]=[],pA[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=pA[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{hA.add(e,t);const i=pA[e];delete pA[e];for(let e=0,s=i.length;e{const i=pA[e];if(void 0===i)throw this.manager.itemError(e),t;delete pA[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class gA{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let mA=0;class _A{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new gA,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new fA;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new fA;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=_A.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(_A.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(_A.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(_A.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),mA>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),mA++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),mA--}}_A.BasisFormat={ETC1S:0,UASTC_4x4:1},_A.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},_A.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},_A.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete vA[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let PA=null;function CA(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=PA[i],o=PA[i+1],n=PA[i+2]),c=Math.min(a=PA[s],l=PA[s+1],A=PA[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let MA=null;function FA(e,t){let i=MA[2*e]-MA[2*t];return 0!==i?i:MA[2*e+1]-MA[2*t+1]}function EA(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(CA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}MA=new Int32Array(e),t.sort(FA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new AA({id:"defaultColorTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new AA({id:"defaultMetalRoughTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new AA({id:"defaultNormalsTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new AA({id:"defaultEmissiveTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new AA({id:"defaultOcclusionTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new lA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||GA),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new AA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new lA({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new kA({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||VA,i=e.position||HA;e.rotation?(c.eulerToQuaternion(e.rotation,"XYZ",QA),e.meshMatrix=c.composeMat4(i,QA,t,c.mat4())):e.meshMatrix=c.composeMat4(i,e.quaternion||jA,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Rr(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):zA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];z(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=Lr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),Lt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Qo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Qo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Cn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new va({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=K),this._pickable&&!1!==e.pickable&&(t|=J),this._culled&&!1!==e.culled&&(t|=X),this._clippable&&!1!==e.clippable&&(t|=Y),this._collidable&&!1!==e.collidable&&(t|=Z),this._edges&&!1!==e.edges&&(t|=te),this._xrayed&&!1!==e.xrayed&&(t|=q),this._highlighted&&!1!==e.highlighted&&(t|=$),this._selected&&!1!==e.selected&&(t|=ee),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class XA extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class oh extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ae(i,t.origin),this._targetMarker=new ae(i,t.target),this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new Ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new Ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new Ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new Ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new ce(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new ce(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new ce(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new ce(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this.useRotationAdjustment=t.useRotationAdjustment}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;de.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&u(e.offsetParent)),d=c.vec2();this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,d),this._markerDiv.style.left=d[0]-5+"px",this._markerDiv.style.top=d[1]-5+"px"):(this._markerDiv.style.left=u(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class lh{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Ah{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=hh(e,i);return s?t?ch(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=hh(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=ch(r,[t]),i&&(r=ch(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function hh(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class dh extends uh{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const ph=c.vec3();const fh=c.vec3(),gh=c.vec3(),mh=c.vec3(),_h=c.vec3(),vh=c.vec3();class bh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?bh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,vh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,mh),s.look=c.subVec3(mh,vh,gh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,gh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,_h)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,mh),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,gh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,_h)),this._projection2){const t="ortho"===this._projection2?bh._easeOutExpo(e,0,1,1):bh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class yh extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new bh(this),this._t=0,this.state=yh.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case yh.SCRUBBING:return;case yh.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=yh.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case yh.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=yh.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=yh.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=yh.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=yh.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=yh.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=yh.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=yh.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}yh.STOPPED=0,yh.SCRUBBING=1,yh.PLAYING=2,yh.PLAYING_TO=3;const xh=c.vec3(),Bh=c.vec3();c.vec3();const wh=c.vec3([0,-1,0]),Ph=c.vec4([0,0,0,1]);function Ch(e){if(!Mh(e.width)||!Mh(e.height)){const t=document.createElement("canvas");t.width=Fh(e.width),t.height=Fh(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Mh(e){return 0==(e&e-1)}function Fh(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Eh extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new tt({texture:new vs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const Dh=c.vec3();const Sh=c.vec3();class Th{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(Sh[0]=this.objectsColorize[3*c+0],Sh[1]=this.objectsColorize[3*c+1],Sh[2]=this.objectsColorize[3*c+2],t.colorize=Sh):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class Lh extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new Ki(this,{geometry:new kt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Ht(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Ps(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const Rh=c.vec4(),Uh=c.vec4(),kh=c.vec3(),Oh=c.vec3(),Nh=c.vec3(),Qh=c.vec4(),Vh=c.vec4(),Hh=c.vec4();class jh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,kh);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),G(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Fs(this._scene,Yi({radius:s})),this._pivotSphere=new Ki(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(G(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Ht(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,Gh)),i=c.cross3Vec3(t,e.worldUp,zh);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=Kh;t.project.unproject(e,a,Xh,Jh,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,Gh)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,zh),Wh);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Zh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Me;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const qh=c.vec2();class $h{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,u=o[2],d=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/d,r.panDeltaY+=1.5*y*i/d}else r.panDeltaX+=.5*t.ortho.scale*(b/d),r.panDeltaY+=.5*t.ortho.scale*(y/d)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/u*i.dragRotationRate/2,r.rotateDeltaX+=y/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/d*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,qh);const i=qh[0],s=qh[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:qh,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,ec);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;oc.orthoScale=g,n?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldRight,f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):a?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldForward,f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):l?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldRight,-f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):A?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldForward,-f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):h?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldUp,f,tc),rc)),oc.look.set(ec),oc.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,ic),sc))):u&&(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldUp,-f,tc),rc)),oc.look.set(ec),oc.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,ic)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(ec),t.cameraFlight.duration>0?t.cameraFlight.flyTo(oc,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(oc),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class ac{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=c.vec3(),i=c.vec3();c.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class lc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Ac=c.vec3();class hc{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,Ac)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{uc(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(uc(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function uc(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const dc=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class pc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(dc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){dc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];dc(t,l),dc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,fc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(fc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(fc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Zh(this,this._configs),pivotController:new Yh(i,this._configs),panController:new jh(i),cameraFlight:new bh(this,{duration:.5})},this._handlers=[new cc(this.scene,this._controllers,this._configs,this._states,this._updates),new pc(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates),new nc(this.scene,this._controllers,this._configs,this._states,this._updates),new ac(this.scene,this._controllers,this._configs,this._states,this._updates),new gc(this.scene,this._controllers,this._configs,this._states,this._updates),new lc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new hc(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?Bc(t):null,n=i&&i.length>0?Bc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(CA);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}MA=new Int32Array(e),t.sort(FA);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new AA({id:"defaultColorTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new AA({id:"defaultMetalRoughTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new AA({id:"defaultNormalsTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new AA({id:"defaultEmissiveTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new AA({id:"defaultOcclusionTexture",texture:new vs({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new lA({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),c.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),c.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||GA),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),c.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),c.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),c.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?_.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new AA({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new lA({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new kA({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?c.addVec3(this._origin,e.origin,c.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||VA,i=e.position||HA;e.rotation?(c.eulerToQuaternion(e.rotation,"XYZ",QA),e.meshMatrix=c.composeMat4(i,QA,t,c.mat4())):e.meshMatrix=c.composeMat4(i,e.quaternion||jA,t,c.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Rr(e.positionsDecodeBoundary,c.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):zA,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=c.vec3(),i=[];z(e.positions,i,t)&&(e.positions=i,e.origin=c.addVec3(e.origin,t,t))}if(e.positions){const t=c.collapseAABB3();e.positionsDecodeMatrix=c.mat4(),c.expandAABB3Points3(t,e.positions),e.positionsCompressed=Lr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=c.collapseAABB3();c.expandAABB3Points3(t,e.positionsCompressed),Lt.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=c.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=c.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new Qo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new Qo({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new Cn({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new va({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=c.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=c.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=K),this._pickable&&!1!==e.pickable&&(t|=J),this._culled&&!1!==e.culled&&(t|=X),this._clippable&&!1!==e.clippable&&(t|=Y),this._collidable&&!1!==e.collidable&&(t|=Z),this._edges&&!1!==e.edges&&(t|=te),this._xrayed&&!1!==e.xrayed&&(t|=q),this._highlighted&&!1!==e.highlighted&&(t|=$),this._selected&&!1!==e.selected&&(t|=ee),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class XA extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class oh extends D{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ae(i,t.origin),this._targetMarker=new ae(i,t.target),this._originWorld=c.vec3(),this._targetWorld=c.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new he(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new Ae(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new Ae(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new Ae(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new Ae(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new ce(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new ce(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new ce(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new ce(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this.useRotationAdjustment=t.useRotationAdjustment}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(c.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){c.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],u=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var d=0,p=s.length;de.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),u=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&u(e.offsetParent)),d=c.vec2();this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,d),this._markerDiv.style.left=d[0]-5+"px",this._markerDiv.style.top=d[1]-5+"px"):(this._markerDiv.style.left=u(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class lh{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){_.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){_.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Ah{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=hh(e,i);return s?t?ch(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=hh(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=ch(r,[t]),i&&(r=ch(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function hh(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=c.subVec3(o,r,[]);return c.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=c.lenVec3(c.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class dh extends uh{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=c.vec3();return A[0]=c.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=c.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=c.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const ph=c.vec3();const fh=c.vec3(),gh=c.vec3(),mh=c.vec3(),_h=c.vec3(),vh=c.vec3();class bh extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=c.vec3(),this._eye1=c.vec3(),this._up1=c.vec3(),this._look2=c.vec3(),this._eye2=c.vec3(),this._up2=c.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,n,a,l,A;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)n=e.eye,a=e.look,l=e.up;else if(e.eye)n=e.eye;else if(e.look)a=e.look;else{let s=e;if((_.isNumeric(s)||_.isString(s))&&(A=s,s=this.scene.components[A],!s))return this.error("Component not found: "+_.inQuotes(A)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const h=e.poi;if(o){if(o[3]=1;e>1&&(e=1);const i=this.easing?bh._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(c.subVec3(s.eye,s.look,vh),s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,mh),s.look=c.subVec3(mh,vh,gh)):this._flyingLook&&(s.look=c.lerpVec3(i,0,1,this._look1,this._look2,gh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,_h)):this._flyingEyeLookUp&&(s.eye=c.lerpVec3(i,0,1,this._eye1,this._eye2,mh),s.look=c.lerpVec3(i,0,1,this._look1,this._look2,gh),s.up=c.lerpVec3(i,0,1,this._up1,this._up2,_h)),this._projection2){const t="ortho"===this._projection2?bh._easeOutExpo(e,0,1,1):bh._easeInCubic(e,0,1,1);s.customProjection.matrix=c.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();M.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class yh extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new bh(this),this._t=0,this.state=yh.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case yh.SCRUBBING:return;case yh.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=yh.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case yh.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=yh.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=yh.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=yh.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=yh.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=yh.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=yh.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=yh.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}yh.STOPPED=0,yh.SCRUBBING=1,yh.PLAYING=2,yh.PLAYING_TO=3;const xh=c.vec3(),Bh=c.vec3();c.vec3();const wh=c.vec3([0,-1,0]),Ph=c.vec4([0,0,0,1]);function Ch(e){if(!Mh(e.width)||!Mh(e.height)){const t=document.createElement("canvas");t.width=Fh(e.width),t.height=Fh(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Mh(e){return 0==(e&e-1)}function Fh(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class Eh extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new tt({texture:new vs({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),p.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const Dh=c.vec3();const Sh=c.vec3();class Th{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?_.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,o=!t||t.xrayed,n=!t||t.highlighted,a=!t||t.selected,l=!t||t.clippable,A=!t||t.pickable,h=!t||t.colorize,c=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),o&&(this.objectsXrayed[u]=t.xrayed),n&&(this.objectsHighlighted[u]=t.highlighted),a&&(this.objectsSelected[u]=t.selected),l&&(this.objectsClippable[u]=t.clippable),A&&(this.objectsPickable[u]=t.pickable),h){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}c&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,o=!t||t.highlighted,n=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,A=!t||t.colorize,h=!t||t.opacity;var c=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[c]),s&&(t.edges=this.objectsEdges[c]),r&&(t.xrayed=this.objectsXrayed[c]),o&&(t.highlighted=this.objectsHighlighted[c]),n&&(t.selected=this.objectsSelected[c]),a&&(t.clippable=this.objectsClippable[c]),l&&(t.pickable=this.objectsPickable[c]),A&&(this.objectsHasColorize[c]?(Sh[0]=this.objectsColorize[3*c+0],Sh[1]=this.objectsColorize[3*c+1],Sh[2]=this.objectsColorize[3*c+2],t.colorize=Sh):t.colorize=null),h&&(t.opacity=this.objectsOpacity[c]),c++}}}class Lh extends D{constructor(e,t={}){super(e,t),this._skyboxMesh=new Ki(this,{geometry:new kt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Ht(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Ps(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}const Rh=c.vec4(),Uh=c.vec4(),kh=c.vec3(),Oh=c.vec3(),Nh=c.vec3(),Qh=c.vec4(),Vh=c.vec4(),Hh=c.vec4();class jh{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=c.subVec3(e,r.eye,kh);s=c.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=c.vec3();c.decomposeMat4(c.inverseMat4(this._scene.viewer.camera.viewMatrix,c.mat4()),t,c.vec4(),c.vec3());const i=c.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),G(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new Fs(this._scene,Yi({radius:s})),this._pivotSphere=new Ki(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){c.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,c.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(G(this.getPivotPos(),this._rtcCenter,this._rtcPos),c.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Ht(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=c.lookAtMat4v(e.eye,e.look,e.worldUp);c.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=c.distVec3(e.eye,i),t=c.inverseMat4(t);const s=c.transformVec3(t,this._cameraOffset),r=c.vec3();if(c.subVec3(e.eye,i,r),c.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=c.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=c.normalizeVec3(c.subVec3(e.look,e.eye,Gh)),i=c.cross3Vec3(t,e.worldUp,zh);return c.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(c.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=c.dotVec4(n,r)/c.dotVec4(n,o),l=Kh;t.project.unproject(e,a,Xh,Jh,l);const A=c.normalizeVec3(c.subVec3(l,t.eye,Gh)),h=c.addVec3(t.eye,c.mulVec3Scalar(A,i,zh),Wh);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=c.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=c.lenVec3(c.subVec3(i.look,i.eye,c.vec3())),a=this.getPivotPos();c.addVec3(o,a);let l=c.lookAtMat4v(o,a,i.worldUp);l=c.inverseMat4(l);const A=c.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],c.subVec3(i.eye,c.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Zh{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=c.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Me;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const qh=c.vec2();class $h{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,u=0,d=0,p=!1;const f=c.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,u=o[2],d=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?c.lenVec3(c.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/d,r.panDeltaY+=1.5*y*i/d}else r.panDeltaX+=.5*t.ortho.scale*(b/d),r.panDeltaY+=.5*t.ortho.scale*(y/d)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/u*i.dragRotationRate/2,r.rotateDeltaX+=y/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/d*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,qh);const i=qh[0],s=qh[1];Math.abs(i-u)<3&&Math.abs(s-d)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:qh,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),u=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||u))return;const d=e.aabb,p=c.getAABB3Diag(d);c.getAABB3Center(d,ec);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*c.DEGTORAD)),g=1.1*p;oc.orthoScale=g,n?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldRight,f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):a?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldForward,f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):l?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldRight,-f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):A?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldForward,-f,tc),rc)),oc.look.set(ec),oc.up.set(o.worldUp)):h?(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldUp,f,tc),rc)),oc.look.set(ec),oc.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,1,ic),sc))):u&&(oc.eye.set(c.addVec3(ec,c.mulVec3Scalar(o.worldUp,-f,tc),rc)),oc.look.set(ec),oc.up.set(c.normalizeVec3(c.mulVec3Scalar(o.worldForward,-1,ic)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(ec),t.cameraFlight.duration>0?t.cameraFlight.flyTo(oc,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(oc),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class ac{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,u=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},d=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=c.vec3(),i=c.vec3();c.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),u=a.hasSubs("hoverOff"),d=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||u||d||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=d,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",d),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),d=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||d||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||d||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(u(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=c.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(u(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=c.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class lc{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const Ac=c.vec3();class hc{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?u=n.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(c.lenVec3(c.subVec3(u,e.camera.eye,Ac)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{uc(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(uc(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function uc(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const dc=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class pc{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=c.vec2(),l=c.vec2(),A=c.vec2(),h=c.vec2(),u=[],d=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),d.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(dc(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));u.length{n.getPivoting()&&n.endPivot()}),d.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],d=n[3],g=t.touches;if(t.touches.length===p){if(1===p){dc(g[0],l),c.subVec2(l,u[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/d*i.touchPanRate,r.panDeltaY+=o*n/d*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/d)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/d)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/d*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];dc(t,l),dc(n,A);const a=c.geometricMeanVec2(u[0],u[1]),h=c.geometricMeanVec2(l,A),p=c.vec2();c.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=c.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(c.distVec2(u[0],u[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(c.lenVec3(c.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/d*i.touchPanRate,r.panDeltaY-=m*s/d*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/d)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/d)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;c.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};d.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,fc(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,d=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(u>-1&&h-u<325?(fc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),u=-1):c.distVec2(l[0],A)<4&&(fc(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=d,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),u=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:c.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:c.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Zh(this,this._configs),pivotController:new Yh(i,this._configs),panController:new jh(i),cameraFlight:new bh(this,{duration:.5})},this._handlers=[new cc(this.scene,this._controllers,this._configs,this._states,this._updates),new pc(this.scene,this._controllers,this._configs,this._states,this._updates),new $h(this.scene,this._controllers,this._configs,this._states,this._updates),new nc(this.scene,this._controllers,this._configs,this._states,this._updates),new ac(this.scene,this._controllers,this._configs,this._states,this._updates),new gc(this.scene,this._controllers,this._configs,this._states,this._updates),new lc(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new hc(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",_.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?Bc(t):null,n=i&&i.length>0?Bc(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-sdk.min.es.js b/dist/xeokit-sdk.min.es.js index 610ec35be..dd92d25a6 100644 --- a/dist/xeokit-sdk.min.es.js +++ b/dist/xeokit-sdk.min.es.js @@ -1,4 +1,4 @@ -class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-85+"px":this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],w=t[4],x=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],L=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=w*s+x*a+P*c+C*f,i[5]=w*r+x*l+P*u+C*g,i[6]=w*o+x*A+P*d+C*m,i[7]=w*n+x*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+L*f,i[13]=D*r+S*l+T*u+L*g,i[14]=D*o+S*A+T*d+L*m,i[15]=D*n+S*h+T*p+L*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,w=r*A-o*l,x=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-B*P+w*x);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*w-g*B+m*y)*I,t[3]=(-c*w+u*B-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*w+g*b-m*v)*I,t[7]=(h*w-u*b+d*v)*I,t[8]=(n*E-a*C+A*x)*I,t[9]=(-i*E+s*C-o*x)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*x)*I,t[13]=(i*M-s*P+r*x)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,B,w;return p=r-h,f=o-c,g=n-u,w=1/Math.sqrt(p*p+f*f+g*g),p*=w,f*=w,g*=w,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,w=Math.sqrt(m*m+_*_+v*v),w?(w=1/w,m*=w,_*=w,v*=w):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,w=Math.sqrt(b*b+y*y+B*B),w?(w=1/w,b*=w,y*=w,B*=w):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],w=e[14],x=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],w=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),i=new l(4),s=new l(4),r=new l(4),o=new l(4);return(n,a,l,A,h,c)=>{const u=d.mulMat4(l,a,e),p=d.inverseMat4(u,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,d.transformVec4(p,i,s),d.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,d.transformVec4(p,r,o),d.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],d.subVec3(o,s,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,e,t),d.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[F.index1],L=i[F.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{w.removeItem(e.id),delete I.scenes[e.id],delete B[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){x.push(e),x.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;x.length>0&&(e<0||s0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),E=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=B[n],s||(s=B[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class L{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof L))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function Q(e,t,i){const s=d.mulMat4(i,t,k),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function V(e,t){let i=N.INSIDE;const s=R,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class H extends L{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==H.PICK_MODE_INSIDE&&e!==H.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===H.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=V(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}H.PICK_MODE_INTERSECTS=0,H.PICK_MODE_INSIDE=1;class j extends L{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}class z{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const W=d.vec3(),K=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function X(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function Y(e,t,i,s=1e3){const r=d.getPositionsCenter(e,W),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){he.set(this._viewPos),he[3]=1,d.transformPoint4(this.scene.camera.projMatrix,he,ce);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ce[0]/ce[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ce[1]/ce[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof Ae?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),X(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const de={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class pe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class fe{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ge{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var me=d.vec3(),_e=d.vec3();class ve extends L{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originMarker=new ue(i,t.origin),this._cornerMarker=new ue(i,t.corner),this._targetMarker=new ue(i,t.target),this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new pe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new pe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new ge(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>u||f>u||g>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&c(e.offsetParent)),u=d.vec2();this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,u),this.markerDiv.style.left=u[0]-5+"px",this.markerDiv.style.top=u[1]-5+"px"):(this.markerDiv.style.left=c(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Be extends z{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ye(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new ve(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

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

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const Pe=d.vec3(),Ce=d.vec3(),Me=d.vec3();class Ee extends z{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){var t,i;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){const s=e.pickResult;if(s.worldPos&&s.worldNormal){const e=d.normalizeVec3(s.worldNormal,Pe),r=d.mulVec3Scalar(e,this._surfaceOffset,Ce);t=d.addVec3(s.worldPos,r,Me),i=s.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var s=null;e.markerElementId&&((s=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var r=null;e.labelElementId&&((r=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const o=new xe(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:s,labelElement:r,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[o.id]=o,o.on("destroyed",(()=>{delete this.annotations[o.id],this.fire("annotationDestroyed",o.id)})),this.fire("annotationCreated",o.id),o}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Ie=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class De extends L{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Fe(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Te.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Te.FS_MAX_FLOAT_PRECISION="mediump":Te.FS_MAX_FLOAT_PRECISION="lowp":Te.FS_MAX_FLOAT_PRECISION="mediump",Te.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Te.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Te.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Te.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Te.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Te.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Te.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Te.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Te.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Te.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Te.SUPPORTED_EXTENSIONS[e]=!0})))}class Re{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Ue{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Ve(e){console.error(e.join("\n"))}class He{constructor(e,t){this.id=Ne.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Ue(e,e.VERTEX_SHADER,Qe(this.source.vertex)),this._fragmentShader=new Ue(e,e.FRAGMENT_SHADER,Qe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ve(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ve(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ve(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ve(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void Ve(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ge{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Ge(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Ge(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new He(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;Xe[0]=o,Xe[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Xe),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new He(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new je(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new je(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new je(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Je=new Float32Array(it(17,[0,1])),Ze=new Float32Array(it(17,[1,0])),qe=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(tt(s,t));return i}(17,4)),$e=new Float32Array(2);class et{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new He(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new je(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new je(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new je(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),$e[0]=n,$e[1]=a,s.uniform2fv(this._uViewport,$e),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ze):s.uniform2fv(this._uSampleOffsets,Je),s.uniform1fv(this._uSampleWeights,qe);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function tt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function it(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class st{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class rt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new st(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function ot(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const nt=function(t,i){i=i||{};const s=new Se(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=!0,u=!0,p=!0,f=!0,g=!0,_=!0,v=!0,b=!0;const y=new rt(t);let B=!1;const w=new Ye(t),x=new et(t);function P(){c&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),c=!1,u=!0),u&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),u=!1,p=!0),p&&function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||j>0||O>0||N>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(O>0||N>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),N>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||z>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),z>0)for(S=0;S0)for(S=0;S0||K>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),K>0)for(S=0;S0)for(S=0;S0||Y>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),Y>0)for(S=0;S0)for(S=0;S0||Z>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Z>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=u.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let D=null,S=null,T=null,L=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),L=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;S=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),D=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===B&&null==D)return null;let R=null;null!==D&&(R=t.camera.projectWorldPos(D));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===L,h.snappedToVertex="vertex"===L,h.worldPos=D,h.worldNormal=S,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=R||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ke(t,y),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){P(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const lt=new e({});class At{constructor(e){this.id=lt.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){lt.removeItem(this.id)}}class ht extends L{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new At({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class ct extends L{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ut extends L{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class dt extends L{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class pt extends L{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ft=d.vec3(),gt=d.vec3(),mt=d.vec3(),_t=d.vec3(),vt=d.vec3(),bt=d.vec3(),yt=d.vec4(),Bt=d.vec4(),wt=d.vec4(),xt=d.mat4(),Pt=d.mat4(),Ct=d.vec3(),Mt=d.vec3(),Et=d.vec3(),Ft=d.vec3();class It extends L{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new At({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new ct(this),this._ortho=new ut(this),this._frustum=new dt(this),this._customProjection=new pt(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(d.subVec3(this._eye,this._look,Ct),d.normalizeVec3(Ct,Mt),d.mulVec3Scalar(Mt,1e3,Et),d.addVec3(this._look,Et,Ft),t=Ft):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Pt),d.mulMat4(e.deviceMatrix,Pt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,ft);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,xt),t=d.transformPoint3(xt,t,gt),this.eye=d.addVec3(this._look,t,mt),this.up=d.transformPoint3(xt,this._up,_t)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ft);const i=d.cross3Vec3(d.normalizeVec3(t,gt),d.normalizeVec3(this._up,mt));d.rotationMat4v(.0174532925*e,i,xt),t=d.transformPoint3(xt,t,_t),this.up=d.transformPoint3(xt,this._up,vt),this.eye=d.addVec3(t,this._look,bt)}yaw(e){let t=d.subVec3(this._look,this._eye,ft);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,xt),t=d.transformPoint3(xt,t,gt),this.look=d.addVec3(t,this._eye,mt),this._gimbalLock&&(this.up=d.transformPoint3(xt,this._up,_t))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ft);const i=d.cross3Vec3(d.normalizeVec3(t,gt),d.normalizeVec3(this._up,mt));d.rotationMat4v(.0174532925*e,i,xt),this.up=d.transformPoint3(xt,this._up,bt),t=d.transformPoint3(xt,t,_t),this.look=d.addVec3(t,this._eye,vt)}pan(e){const t=d.subVec3(this._eye,this._look,ft),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,gt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,mt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,_t),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,vt),this.look=d.addVec3(this._look,i,bt)}zoom(e){const t=d.subVec3(this._eye,this._look,ft),i=Math.abs(d.lenVec3(t,gt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,mt);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),_t)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,ft))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=yt,i=Bt,s=wt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Dt extends L{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class St extends Dt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new At({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new st(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Tt extends Dt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Lt extends L{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var Rt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[F.index1],L=i[F.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}();const Ut=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var kt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Qt(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Vt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Ht={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Nt(e,a,"floor","ceil"),s=Qt(i),o=Vt(e,a,s),o>n&&(r=i,n=o),i=Nt(e,a,"ceil","ceil"),s=Qt(i),o=Vt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},jt=m.memory,Gt=d.AABB3();class zt extends Lt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new At({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Ht.getPositionsBounds(t.positions),s=Ht.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Ht.getUVBounds(t.uv),s=Ht.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Ht.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),jt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),jt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new je(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),jt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new je(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),jt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new je(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),jt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new je(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),jt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Rt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),jt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new je(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),jt.positions+=this._pickTrianglePositionsBuf.numItems,jt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Ht.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Ht.getPositionsBounds(e),s=Ht.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Ht.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Ht.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,Gt,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(Gt,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),jt.meshes--}}function Wt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Kt extends L{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const Xt={opaque:0,mask:1,blend:2},Yt=["opaque","mask","blend"];class Jt extends Kt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new At({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Xt[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 Yt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Zt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class qt extends Kt{get type(){return"EmphasisMaterial"}get presets(){return Zt}constructor(e,t={}){super(e,t),this._state=new At({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Zt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Zt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const $t={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class ei extends Kt{get type(){return"EdgeMaterial"}get presets(){return $t}constructor(e,t={}){super(e,t),this._state=new At({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=$t[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys($t).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const ti={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class ii extends L{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ti}set units(e){e||(e="meters");ti[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class si extends L{constructor(e,t={}){super(e,t),this._supported=Te.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class ri extends L{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const oi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class ni extends Kt{get type(){return"PointsMaterial"}get presets(){return oi}constructor(e,t={}){super(e,t),this._state=new At({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=oi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(oi).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const ai={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class li extends Kt{get type(){return"LinesMaterial"}get presets(){return ai}constructor(e,t={}){super(e,t),this._state=new At({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ai[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ai).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ai(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new nt(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=Ai(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Ai(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ci=1e3,ui=1001,di=1002,pi=1003,fi=1004,gi=1004,mi=1005,_i=1005,vi=1006,bi=1007,yi=1007,Bi=1008,wi=1008,xi=1009,Pi=1010,Ci=1011,Mi=1012,Ei=1013,Fi=1014,Ii=1015,Di=1016,Si=1017,Ti=1018,Li=1020,Ri=1021,Ui=1022,ki=1023,Oi=1024,Ni=1025,Qi=1026,Vi=1027,Hi=1028,ji=1029,Gi=1030,zi=1031,Wi=1033,Ki=33776,Xi=33777,Yi=33778,Ji=33779,Zi=35840,qi=35841,$i=35842,es=35843,ts=36196,is=37492,ss=37496,rs=37808,os=37809,ns=37810,as=37811,ls=37812,As=37813,hs=37814,cs=37815,us=37816,ds=37817,ps=37818,fs=37819,gs=37820,ms=37821,_s=36492,vs=3e3,bs=3001,ys=1e4,Bs=10001,ws=10002,xs=10003,Ps=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=Es(e),u=s.getNumAllocatedSectionPlanes()>0,d=Ms(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=Es(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Ms(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Cs[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Cs[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Cs[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Cs[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Cs[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Cs[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Ts{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ls=new e({}),Rs=d.vec3(),Us=function(e,t){this.id=Ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ts(t),this._allocate(t)},ks={};Us.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ks[t];return i||(i=new Us(t,e),ks[t]=i,m.memory.programs++),i._useCount++,i},Us.prototype.put=function(){0==--this._useCount&&(Ls.removeItem(this.id),this._program&&this._program.destroy(),delete ks[this._hash],m.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ns=new e({}),Qs=d.vec3(),Vs=function(e,t){this.id=Ns.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Os(t),this._allocate(t)},Hs={};Vs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Hs[t];return i||(i=new Vs(t,e),Hs[t]=i,m.memory.programs++),i._useCount++,i},Vs.prototype.put=function(){0==--this._useCount&&(Ns.removeItem(this.id),this._program&&this._program.destroy(),delete Hs[this._hash],m.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Gs=d.vec3(),zs=function(e,t){this._hash=e,this._shaderSource=new js(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ws={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Ws[t];if(!i){if(i=new zs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ws[t]=i,m.memory.programs++}return i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ws[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},zs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new He(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Xs=d.vec3(),Ys=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ks(t),this._allocate(t)},Js={};Ys.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Js[t];if(!i){if(i=new Ys(t,e),i.errors)return console.log(i.errors.join("\n")),null;Js[t]=i,m.memory.programs++}return i._useCount++,i},Ys.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Js[this._hash],m.memory.programs--)},Ys.prototype.webglContextRestored=function(){this._program=null},Ys.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const qs=d.vec3(),$s=function(e,t){this._hash=e,this._shaderSource=new Zs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},er={};$s.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=er[t];if(!i){if(i=new $s(t,e),i.errors)return console.log(i.errors.join("\n")),null;er[t]=i,m.memory.programs++}return i._useCount++,i},$s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete er[this._hash],m.memory.programs--)},$s.prototype.webglContextRestored=function(){this._program=null},$s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const ir=function(e,t){this._hash=e,this._shaderSource=new tr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},sr={};ir.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=sr[i];if(!s){if(s=new ir(i,e),s.errors)return console.log(s.errors.join("\n")),null;sr[i]=s,m.memory.programs++}return s._useCount++,s},ir.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete sr[this._hash],m.memory.programs--)},ir.prototype.webglContextRestored=function(){this._program=null},ir.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},ir.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new He(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const gr=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),B=d.vec3(),w=d.vec3(),x=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),I=d.vec3();return function(D,S,T,L){var R=L.primIndex;if(null!=R&&R>-1){const N=D.geometry._state,Q=D.scene,V=Q.camera,H=Q.canvas;if("triangles"===N.primitiveName){L.primitive="triangle";const Q=R,j=N.indices,G=N.positions;let z,W,X;if(j){var U=j[Q+0],k=j[Q+1],O=j[Q+2];o[0]=U,o[1]=k,o[2]=O,L.indices=o,z=3*U,W=3*k,X=3*O}else z=3*Q,W=z+3,X=W+3;if(i[0]=G[z+0],i[1]=G[z+1],i[2]=G[z+2],s[0]=G[W+0],s[1]=G[W+1],s[2]=G[W+2],r[0]=G[X+0],r[1]=G[X+1],r[2]=G[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Ht.decompressPosition(i,e,i),Ht.decompressPosition(s,e,s),Ht.decompressPosition(r,e,r))}L.canvasPos?d.canvasPosToLocalRay(H.canvas,D.origin?K(S,D.origin):S,T,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&d.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,d.transformVec4(V.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=N.normals;if(Y){if(N.compressGeometry){const e=3*U,t=3*k,i=3*O;Ht.decompressNormal(Y.subarray(e,e+2),h),Ht.decompressNormal(Y.subarray(t,t+2),c),Ht.decompressNormal(Y.subarray(i,i+2),u)}else h[0]=Y[z],h[1]=Y[z+1],h[2]=Y[z+2],c[0]=Y[W],c[1]=Y[W+1],c[2]=Y[W+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),B),d.mulVec3Scalar(u,A[2],w),x);L.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const J=N.uv;if(J){if(p[0]=J[2*U],p[1]=J[2*U+1],f[0]=J[2*k],f[1]=J[2*k+1],g[0]=J[2*O],g[1]=J[2*O+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Ht.decompressUV(p,e,p),Ht.decompressUV(f,e,f),Ht.decompressUV(g,e,g))}L.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),E),d.mulVec2Scalar(g,A[2],F),I)}}}}}();function mr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,B,w,x,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),m.push(P*w),m.push(S),m.push(P*x),_.push(B*p),_.push(1*b/o),g.push(P*w+l),g.push(C+A),g.push(P*x+h);for(b=0;b0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*w),m.push(1),m.push(t*x),_.push(I),_.push(D),g.push(t*w+l),g.push(c+A),g.push(t*x+h);for(B=0;B0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*w),m.push(-1),m.push(i*x),_.push(I),_.push(D),g.push(i*w+l),g.push(0-c+A),g.push(i*x+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function br(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,B=.04,w=0;w<_.length;w++){A=0,c=(h=_[w]).length;for(var x=0;x0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Qr(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Qr(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Qr(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Gr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Gr(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Qr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Qr(i,this.magFilter)));const a=Qr(i,this.format,this.encoding),l=Qr(i,this.type),A=jr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Xr extends L{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new At({texture:new Hr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Hr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=zr(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=zr(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class Yr extends L{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new At({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const Jr=m.memory,Zr=d.AABB3();class qr extends Lt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new At({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Ht.getPositionsBounds(t.positions),o=Ht.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new je(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Jr.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,Zr,i.positionsDecodeMatrix),d.AABB3ToOBB3(Zr,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new je(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Jr.colors+=i.colorsBuf.numItems}if(t.uv){const e=Ht.getUVBounds(t.uv),r=Ht.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new je(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Jr.uvs+=i.uvBuf.numItems}if(t.normals){const e=Ht.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new je(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Jr.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Jr.indices+=i.indicesBuf.numItems;const o=Rt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Jr.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(),Jr.meshes--}}var $r={};function eo(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=$r.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function to(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=$r.parse.fromOBJ(e),n=$r.edit.unwrap(o.i_verts,o.c_verts,3),a=$r.edit.unwrap(o.i_norms,o.c_norms,3),l=$r.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function io(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function so(e={}){return io({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function ro(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function oo(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,B,w,x,P,C,M,E=0,F=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,B,w,x,P,C,M;for(w=0;w<=r;w++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+w/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-B/s),u.push(w/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(w=1;w<=r;w++)for(B=1;B<=s;B++)x=(s+1)*w+B-1,P=(s+1)*(w-1)+B-1,C=(s+1)*(w-1)+B,M=(s+1)*w+B,p.push(x),p.push(P),p.push(C),p.push(C),p.push(M),p.push(x);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function ao(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return ao({id:e.id,points:t})}$r.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},$r.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa($r.parse._buffToStr(e));window.location.href=i},$r.clone=function(e){return JSON.parse(JSON.stringify(e))},$r.bin={},$r.bin.f=new Float32Array(1),$r.bin.fb=new Uint8Array($r.bin.f.buffer),$r.bin.rf=function(e,t){for(var i=$r.bin.f,s=$r.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},$r.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},$r.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},$r.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},$r.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},$r.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},$r.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},$r.parse={},$r.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Ao extends L{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new Xr(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Sr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new fr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new zt(this,oo({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const ho=d.OBB3(),co=d.OBB3(),uo=d.OBB3();class po{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(d.AABB3ToOBB3(this._aabbLocal,ho),this.transform?(d.transformOBB3(this.transform.worldMatrix,ho,co),d.transformOBB3(this.model.worldMatrix,co,uo),d.OBB3ToAABB3(uo,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,ho,co),d.OBB3ToAABB3(co,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const fo=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 go=0;const mo={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},_o=new Float32Array([1,1,1,1]),vo=new Float32Array([0,0,0,1]),bo=d.vec4(),yo=d.vec3(),Bo=d.vec3(),wo=d.mat4();class xo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;bo[0]=i,bo[1]=s,bo[2]=t.blendCutoff,bo[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,bo),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?vo:_o)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class Po extends xo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Co extends Po{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Mo extends Po{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class Fo extends Po{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class Io extends Fo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Do extends Fo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class So extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class To extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Lo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Ro extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Uo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class ko extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Oo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class No extends Po{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Vo extends Po{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xo=d.vec3(),Yo=d.vec3(),Jo=d.vec3(),Zo=d.vec3(),qo=d.mat4();class $o extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Xo;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Yo;if(l){const e=Jo;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,qo),m=Zo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class en{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Eo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new So(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new To(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new $o(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Co(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Co(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Mo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Mo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Vo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Vo(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new No(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new No(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Eo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Uo(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ko(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Io(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Do(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new So(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Lo(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Qo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new To(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ro(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Oo(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new $o(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const tn={};let sn=65536,rn=5e6;class on{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),sn=e}get maxDataTextureHeight(){return sn}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),rn=e}get maxGeometryBatchSize(){return rn}}const nn=new on;class an{constructor(){this.maxVerts=nn.maxGeometryBatchSize,this.maxIndices=3*nn.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ln=d.mat4(),An=d.mat4();function hn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function dn(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const pn=d.mat4(),fn=d.mat4(),gn=d.vec4([0,0,0,1]),mn=d.vec3(),_n=d.vec3(),vn=d.vec3(),bn=d.vec3(),yn=d.vec3(),Bn=d.vec3(),wn=d.vec3();class xn{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=tn[t];return i||(i=new en(e),tn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete tn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new an(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=pn;m?d.inverseMat4(d.transposeMat4(m,fn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=un(p,"floor","ceil"),a=dn(n),A=o(p,a),A>h&&(l=n,h=A),n=un(p,"ceil","ceil"),a=dn(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):hn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new je(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new je(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Ht.getUVBounds(i.uv),r=Ht.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new je(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new je(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new je(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Pn extends xo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Cn extends Pn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Mn extends Pn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class Fn extends Pn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class In extends Fn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Dn extends Fn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Sn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Tn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Ln extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Rn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Un extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class kn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class On extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Nn={3e3:"linearToLinear",3001:"sRGBToLinear"};class Qn extends Pn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Nn[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Nn[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Hn extends Pn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yn=d.vec3(),Jn=d.vec3(),Zn=d.vec3(),qn=d.vec3(),$n=d.mat4();class ea extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Yn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Jn;if(l){const e=d.transformPoint3(h,l,Zn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,$n),m=qn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ta{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Sn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Tn(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Xn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ea(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Cn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Mn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Mn(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Qn(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Qn(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Hn(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Hn(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Un(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new kn(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new In(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Dn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Sn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ln(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Vn(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Tn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Rn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new On(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ea(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const ia={};const sa=new Uint8Array(4),ra=new Float32Array(1),oa=d.vec4([0,0,0,1]),na=new Float32Array(3),aa=d.vec3(),la=d.vec3(),Aa=d.vec3(),ha=d.vec3(),ca=d.vec3(),ua=d.vec3(),da=d.vec3(),pa=new Float32Array(4);class fa{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=ia[t];return i||(i=new ta(e),ia[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete ia[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new je(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new je(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new je(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new je(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new je(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new je(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new je(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";sa[0]=t[0],sa[1]=t[1],sa[2]=t[2],sa[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(sa,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?1:0)<<16,ra[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(ra,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(na[0]=t[0],na[1]=t[1],na[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(na,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],c=oa,u=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ga extends xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class ma extends ga{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class _a extends ga{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const va=d.vec3(),ba=d.vec3(),ya=d.vec3(),Ba=d.vec3(),wa=d.mat4();class xa extends xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=va;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ba;if(l){const e=ya;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,wa),m=Ba,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pa=d.vec3(),Ca=d.vec3(),Ma=d.vec3(),Ea=d.vec3(),Fa=d.mat4();class Ia extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Pa;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ca;if(l){const e=Ma;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Fa),m=Ea,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Da{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ma(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _a(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new xa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Sa={};class Ta{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class La{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Sa[t];return i||(i=new Da(e),Sa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Sa[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Ta(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=hn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class ka extends Ra{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Oa=d.vec3(),Na=d.vec3(),Qa=d.vec3();d.vec3();const Va=d.mat4();class Ha extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Oa;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Na;if(l){const e=d.transformPoint3(h,l,Qa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Va),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ja=d.vec3(),Ga=d.vec3(),za=d.vec3();d.vec3();const Wa=d.mat4();class Ka extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ja;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ga;if(l){const e=d.transformPoint3(h,l,za);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Wa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Ha(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ka(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ua(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ka(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ha(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ka(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ya={};const Ja=new Uint8Array(4),Za=new Float32Array(1),qa=new Float32Array(3),$a=new Float32Array(4);class el{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ya[t];return i||(i=new Xa(e),Ya[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Ya[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new je(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new je(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new je(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new je(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ja[0]=t[0],Ja[1]=t[1],Ja[2]=t[2],Ja[3]=t[3],this._state.colorsBuf.setData(Ja,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?255:0)<<16,Za[0]=d,this._state.flagsBuf.setData(Za,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qa[0]=t[0],qa[1]=t[1],qa[2]=t[2],this._state.offsetsBuf.setData(qa,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;$a[0]=t[0],$a[1]=t[4],$a[2]=t[8],$a[3]=t[12],this._state.modelMatrixCol0Buf.setData($a,i),$a[0]=t[1],$a[1]=t[5],$a[2]=t[9],$a[3]=t[13],this._state.modelMatrixCol1Buf.setData($a,i),$a[0]=t[2],$a[1]=t[6],$a[2]=t[10],$a[3]=t[14],this._state.modelMatrixCol2Buf.setData($a,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class tl extends xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class il extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class sl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class rl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class ol extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class nl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const al=d.vec3(),ll=d.vec3(),Al=d.vec3(),hl=d.vec3(),cl=d.mat4();class ul extends xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=al;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ll;if(l){const e=Al;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,cl),m=hl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dl=d.vec3(),pl=d.vec3(),fl=d.vec3(),gl=d.vec3(),ml=d.mat4();class _l extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=dl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=pl;if(l){const e=fl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,ml),m=gl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class vl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new il(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new sl(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new rl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ol(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nl(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const bl={};class yl{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class Bl{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=bl[t];return i||(i=new vl(e),bl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete bl[t],i._destroy()}))),i}(e.model.scene),this._buffer=new yl(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=hn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new je(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Pl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Cl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Ml extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class El extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Fl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Il extends wl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Dl=d.vec3(),Sl=d.vec3(),Tl=d.vec3();d.vec3();const Ll=d.mat4();class Rl extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sl;if(l){const e=d.transformPoint3(h,l,Tl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Ll),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ul=d.vec3(),kl=d.vec3(),Ol=d.vec3();d.vec3();const Nl=d.mat4();class Ql extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ul;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=kl;if(l){const e=d.transformPoint3(h,l,Ol);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Nl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new xl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Fl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Cl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ml(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new El(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Il(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Rl(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ql(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Hl={};const jl=new Uint8Array(4),Gl=new Float32Array(1),zl=new Float32Array(3),Wl=new Float32Array(4);class Kl{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Hl[t];return i||(i=new Vl(e),Hl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Hl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new je(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new je(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new je(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";jl[0]=t[0],jl[1]=t[1],jl[2]=t[2],this._state.colorsBuf.setData(jl,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?255:0)<<16,Gl[0]=d,this._state.flagsBuf.setData(Gl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(zl[0]=t[0],zl[1]=t[1],zl[2]=t[2],this._state.offsetsBuf.setData(zl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Wl[0]=t[0],Wl[1]=t[4],Wl[2]=t[8],Wl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Wl,i),Wl[0]=t[1],Wl[1]=t[5],Wl[2]=t[9],Wl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Wl,i),Wl[0]=t[2],Wl[1]=t[6],Wl[2]=t[10],Wl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Wl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,mo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,mo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Xl=d.vec3(),Yl=d.vec3(),Jl=d.mat4();class Zl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Xl;if(g){const t=d.transformPoint3(c,A,Yl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,Jl)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ql{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Zl(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const $l={};class eA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class tA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class iA{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const sA={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(sA,null,4));let e=0;Object.keys(sA).forEach((t=>{t.startsWith("size")&&(e+=sA[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/sA.totalLines).toFixed(2)}`);let t={};Object.keys(sA).forEach((i=>{i.startsWith("size")&&(t[i]=`${(sA[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class rA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);sA.sizeDataColorsAndFlags+=l.byteLength,sA.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);sA.sizeDataTextureOffsets+=r.byteLength,sA.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);sA.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete $l[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new eA,this._dataTextureState=new tA,this._dataTextureGenerator=new rA,this._state=new At({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&sA.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*nA||t+r>4096*nA)&&sA.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*nA&&t+r<=4096*nA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;sA.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,sA.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||cA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,sA.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,sA.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,sA.totalLines32Bits+=t.numLines),sA.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,lA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,lA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,lA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,AA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,aA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const dA=d.vec3(),pA=d.vec3(),fA=d.vec3();d.vec3();const gA=d.vec4(),mA=d.mat4();class _A{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=dA;if(g){const t=d.transformPoint3(c,A,pA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,mA),f=fA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new He(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vA=new Float32Array([1,1,1]),bA=d.vec3(),yA=d.vec3(),BA=d.vec3();d.vec3();const wA=d.mat4();class xA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=bA;if(A){const t=yA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,wA),g=BA,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===mo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,vA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const PA=new Float32Array([0,0,0,1]),CA=d.vec3(),MA=d.vec3();d.vec3();const EA=d.mat4();class FA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=CA;if(g){const t=d.transformPoint3(c,A,MA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,EA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===mo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,PA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const IA=d.vec3(),DA=d.vec3(),SA=d.mat4();class TA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=IA;if(g){const t=d.transformPoint3(c,A,DA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,SA)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const LA=d.vec3(),RA=d.vec3(),UA=d.vec3(),kA=d.mat4();class OA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=LA;if(g){const t=d.transformPoint3(c,A,RA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(o.viewMatrix,e,kA),f=UA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const NA=d.vec3(),QA=d.vec3(),VA=d.vec3();d.vec3();const HA=d.mat4();class jA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=NA;if(A){const e=QA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=K(p,t,HA),g=VA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const GA=d.vec3(),zA=d.vec3(),WA=d.vec3(),KA=d.vec3();d.vec3();const XA=d.mat4();class YA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=GA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=zA;if(v){const e=d.transformPoint3(c,A,WA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,XA),_=KA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(w,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(w,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(w,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const JA=d.vec3(),ZA=d.vec3(),qA=d.vec3(),$A=d.vec3();d.vec3();const eh=d.mat4();class th{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=JA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ZA;if(v){const e=qA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,eh),_=$A,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ih=d.vec3(),sh=d.vec3(),rh=d.vec3();d.vec3();const oh=d.mat4();class nh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ih;if(A){const t=sh;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,oh),g=rh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ah=d.vec3(),lh=d.vec3(),Ah=d.vec3();d.vec3();const hh=d.mat4();class ch{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ah;if(g){const t=d.transformPoint3(c,A,lh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,hh),f=Ah,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const uh=d.vec3(),dh=d.vec3(),ph=d.vec3();d.vec3();const fh=d.mat4();class gh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=uh;if(g){const t=dh;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=K(u,e,fh),f=ph,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Te.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const mh=d.vec3(),_h=d.vec3(),vh=d.vec3();d.vec3(),d.vec4();const bh=d.mat4();class yh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=mh;if(g){const t=d.transformPoint3(c,A,_h);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,bh),f=vh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Bh{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new xA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new OA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new jA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new yh(this._scene)),this._snapRenderer||(this._snapRenderer=new YA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new th(this._scene)),this._snapRenderer||(this._snapRenderer=new YA(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _A(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _A(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ch(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new gh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new FA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new TA(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new OA(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new yh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new yh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new jA(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new YA(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new th(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nh(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const wh={};class xh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Ph{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Ch={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ch,null,4));let e=0;Object.keys(Ch).forEach((t=>{t.startsWith("size")&&(e+=Ch[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ch.totalPolygons).toFixed(2)}`);let t={};Object.keys(Ch).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ch[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Mh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Ch.sizeDataColorsAndFlags+=h.byteLength,Ch.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ch.sizeDataTextureOffsets+=r.byteLength,Ch.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ch.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new xh,this._dtxState=new Ph,this._dtxTextureFactory=new Mh,this._state=new At({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ch.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*Fh||t+r>4096*Fh)&&Ch.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Fh&&t+r<=4096*Fh}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Ch.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Ch.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Ch.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||Lh),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Ch.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Ch.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Ch.totalPolygons32Bits+=t.numTriangles),Ch.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Ch.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Ch.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Ch.totalEdges32Bits+=t.numEdges),Ch.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Dh)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,Dh))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Dh))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Sh))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ih))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,mo.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,mo.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,mo.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,mo.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,mo.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,mo.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class Uh{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 kh{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Oh={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 Nh{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==Hh[e])return void Hh[e].push({onLoad:t,onProgress:i,onError:s});Hh[e]=[],Hh[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=Hh[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{Oh.add(e,t);const i=Hh[e];delete Hh[e];for(let e=0,s=i.length;e{const i=Hh[e];if(void 0===i)throw this.manager.itemError(e),t;delete Hh[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Gh{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let zh=0;class Wh{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Gh,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new jh;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new jh;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Wh.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Wh.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Wh.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Wh.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),zh>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),zh++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),zh--}}Wh.BasisFormat={ETC1S:0,UASTC_4x4:1},Wh.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},Wh.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},Wh.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete Kh[t],i.destroy()}))),i} +class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&(document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e{const o=this._getNextId(),n=new i(o);for(let i=0,o=e.length;i0,A=this._getNextId(),h=i.getTitle||(()=>i.title||""),c=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),p=new r(A,h,c,u,d);if(p.parentMenu=n,a.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(n),this._menuMap[n.id]=n,n};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t'),i.push("
    "),t)for(let e=0,s=t.length;e'+l+" [MORE]"):i.push('
  • '+l+"
  • ")}}i.push("
"),i.push("");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let n=null;if(t)for(let e=0,i=t.length;e{e.preventDefault();const i=t.subMenu;if(!i)return void(n&&(o._hideMenu(n.id),n=null));if(n&&n.id!==i.id&&(o._hideMenu(n.id),n=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,a=s.getBoundingClientRect();r.getBoundingClientRect();a.right+200>window.innerWidth?o._showMenu(i.id,a.left-200,a.top-1):o._showMenu(i.id,a.right-5,a.top-1),n=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),o._context&&!1!==t.enabled&&(t.doAction&&t.doAction(o._context),this._hideOnAction?o.hide():(o._updateItemsTitles(),o._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;ewindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class n{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-85+"px":this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){const e=this._snappedCanvasPos[0]-this._canvasPos[0],t=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft=r[0]+e*this._zoomLevel-10+"px",this._lensCursorDiv.style.marginTop=r[1]+t*this._zoomLevel-10+"px"}else this._lensCursorDiv.style.marginLeft=r[0]-10+"px",this._lensCursorDiv.style.marginTop=r[1]-10+"px"}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}get snapped(){return this._snapped}set active(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get active(){return this._active}set visible(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let a=!0,l=a?Float64Array:Float32Array;const A=new l(3),h=new l(16),c=new l(16),u=new l(4),d={setDoublePrecisionEnabled(e){a=e,l=a?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>a,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new l(e||2),vec3:e=>new l(e||3),vec4:e=>new l(e||4),mat3:e=>new l(e||9),mat3ToMat4:(e,t=new l(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new l(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new l(2);for(let r=0,o=e.length;r{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(ee[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new l(e[0]);for(let i=1;i(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],n=t[1],a=t[2];return[s*a-r*n,r*o-i*a,i*n-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=t[0],a=t[1],l=t[2];return i[0]=r*l-o*a,i[1]=o*n-s*l,i[2]=s*a-r*n,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new l(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new l(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new l(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new l([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new l(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new l(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],n=e[3],a=e[4],l=e[5],A=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],f=e[12],g=e[13],m=e[14],_=e[15],v=t[0],b=t[1],y=t[2],B=t[3],w=t[4],x=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],I=t[11],D=t[12],S=t[13],T=t[14],L=t[15];return i[0]=v*s+b*a+y*c+B*f,i[1]=v*r+b*l+y*u+B*g,i[2]=v*o+b*A+y*d+B*m,i[3]=v*n+b*h+y*p+B*_,i[4]=w*s+x*a+P*c+C*f,i[5]=w*r+x*l+P*u+C*g,i[6]=w*o+x*A+P*d+C*m,i[7]=w*n+x*h+P*p+C*_,i[8]=M*s+E*a+F*c+I*f,i[9]=M*r+E*l+F*u+I*g,i[10]=M*o+E*A+F*d+I*m,i[11]=M*n+E*h+F*p+I*_,i[12]=D*s+S*a+T*c+L*f,i[13]=D*r+S*l+T*u+L*g,i[14]=D*o+S*A+T*d+L*m,i[15]=D*n+S*h+T*p+L*_,i},mulMat3(e,t,i){i||(i=new l(9));const s=e[0],r=e[3],o=e[6],n=e[1],a=e[4],A=e[7],h=e[2],c=e[5],u=e[8],d=t[0],p=t[3],f=t[6],g=t[1],m=t[4],_=t[7],v=t[2],b=t[5],y=t[8];return i[0]=s*d+r*g+o*v,i[3]=s*p+r*m+o*b,i[6]=s*f+r*_+o*y,i[1]=n*d+a*g+A*v,i[4]=n*p+a*m+A*b,i[7]=n*f+a*_+A*y,i[2]=h*d+c*g+u*v,i[5]=h*p+c*m+u*b,i[8]=h*f+c*_+u*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],o=t[2],n=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*n,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*n,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*n,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*n,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],n=e[12],a=e[9];if(!t||e===t){const t=e[1],l=e[2],A=e[3],h=e[6],c=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=n,e[4]=t,e[6]=a,e[7]=o,e[8]=l,e[9]=h,e[11]=s,e[12]=A,e[13]=c,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=n,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],n=e[5],a=e[6],l=e[7],A=e[8],h=e[9],c=e[10],u=e[11],d=e[12],p=e[13],f=e[14],g=e[15];return d*h*a*r-A*p*a*r-d*n*c*r+o*p*c*r+A*n*f*r-o*h*f*r-d*h*s*l+A*p*s*l+d*i*c*l-t*p*c*l-A*i*f*l+t*h*f*l+d*n*s*u-o*p*s*u-d*i*a*u+t*p*a*u+o*i*f*u-t*n*f*u-A*n*s*g+o*h*s*g+A*i*a*g-t*h*a*g-o*i*c*g+t*n*c*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],n=e[4],a=e[5],l=e[6],A=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],f=e[13],g=e[14],m=e[15],_=i*a-s*n,v=i*l-r*n,b=i*A-o*n,y=s*l-r*a,B=s*A-o*a,w=r*A-o*l,x=h*f-c*p,P=h*g-u*p,C=h*m-d*p,M=c*g-u*f,E=c*m-d*f,F=u*m-d*g,I=1/(_*F-v*E+b*M+y*C-B*P+w*x);return t[0]=(a*F-l*E+A*M)*I,t[1]=(-s*F+r*E-o*M)*I,t[2]=(f*w-g*B+m*y)*I,t[3]=(-c*w+u*B-d*y)*I,t[4]=(-n*F+l*C-A*P)*I,t[5]=(i*F-r*C+o*P)*I,t[6]=(-p*w+g*b-m*v)*I,t[7]=(h*w-u*b+d*v)*I,t[8]=(n*E-a*C+A*x)*I,t[9]=(-i*E+s*C-o*x)*I,t[10]=(p*B-f*b+m*_)*I,t[11]=(-h*B+c*b-d*_)*I,t[12]=(-n*M+a*P-l*x)*I,t[13]=(i*M-s*P+r*x)*I,t[14]=(-p*y+f*v-g*_)*I,t[15]=(h*y-c*v+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const n=s[11];s[8]+=n*e,s[9]+=n*t,s[10]+=n*i;const a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),n=1-o,a=s[0],l=s[1],A=s[2];let h,c,u,p,f,g;return h=a*l,c=l*A,u=A*a,p=a*r,f=l*r,g=A*r,(i=i||d.mat4())[0]=n*a*a+o,i[1]=n*h+g,i[2]=n*u-f,i[3]=0,i[4]=n*h-g,i[5]=n*l*l+o,i[6]=n*c+p,i[7]=0,i[8]=n*u+f,i[9]=n*c-p,i[10]=n*A*A+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new l(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=s+s,l=r+r,A=o+o,h=s*a,c=s*l,u=s*A,p=r*l,f=r*A,g=o*A,m=n*a,_=n*l,v=n*A;return i[0]=1-(p+g),i[1]=c+v,i[2]=u-_,i[3]=0,i[4]=c-v,i[5]=1-(h+g),i[6]=f+m,i[7]=0,i[8]=u+_,i[9]=f-m,i[10]=1-(h+p),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],o=e[4],n=e[8],a=e[1],l=e[5],A=e[9],h=e[2],c=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-A,u),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[1]=Math.atan2(n,u),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-h,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-h,u),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[0]=Math.atan2(c,u),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-A,l),i[1]=Math.atan2(-h,r)):(i[0]=0,i[1]=Math.atan2(n,u))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(n,r)):(i[0]=Math.atan2(-A,u),i[1]=0)),i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new l(3),t=new l(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let n=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const a=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=d.lenVec3(e);d.determinantMat4(i)<0&&(n=-n),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const A=1/n,h=1/a,c=1/l;return t[0]*=A,t[1]*=A,t[2]*=A,t[4]*=h,t[5]*=h,t[6]*=h,t[8]*=c,t[9]*=c,t[10]*=c,d.mat4ToQuaternion(t,r),o[0]=n,o[1]=a,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],o=e[1],n=e[2],a=i[0],l=i[1],A=i[2],h=t[0],c=t[1],u=t[2];if(r===h&&o===c&&n===u)return d.identityMat4();let p,f,g,m,_,v,b,y,B,w;return p=r-h,f=o-c,g=n-u,w=1/Math.sqrt(p*p+f*f+g*g),p*=w,f*=w,g*=w,m=l*g-A*f,_=A*p-a*g,v=a*f-l*p,w=Math.sqrt(m*m+_*_+v*v),w?(w=1/w,m*=w,_*=w,v*=w):(m=0,_=0,v=0),b=f*v-g*_,y=g*m-p*v,B=p*_-f*m,w=Math.sqrt(b*b+y*y+B*B),w?(w=1/w,b*=w,y*=w,B*=w):(b=0,y=0,B=0),s[0]=m,s[1]=b,s[2]=p,s[3]=0,s[4]=_,s[5]=y,s[6]=f,s[7]=0,s[8]=v,s[9]=B,s[10]=g,s[11]=0,s[12]=-(m*r+_*o+v*n),s[13]=-(b*r+y*o+B*n),s[14]=-(p*r+f*o+g*n),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,n,a,l)=>d.lookAtMat4v([e,t,i],[s,r,o],[n,a,l],[]),orthoMat4c(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2/l,n[6]=0,n[7]=0,n[8]=0,n[9]=0,n[10]=-2/A,n[11]=0,n[12]=-(e+t)/a,n[13]=-(s+i)/l,n[14]=-(o+r)/A,n[15]=1,n},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,h),d.subVec4(r,s,c);const o=2*s[2],n=c[0],a=c[1],l=c[2];return i[0]=o/n,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/a,i[6]=0,i[7]=0,i[8]=h[0]/n,i[9]=h[1]/a,i[10]=-h[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/l,i[15]=0,i},frustumMat4(e,t,i,s,r,o,n){n||(n=d.mat4());const a=t-e,l=s-i,A=o-r;return n[0]=2*r/a,n[1]=0,n[2]=0,n[3]=0,n[4]=0,n[5]=2*r/l,n[6]=0,n[7]=0,n[8]=(t+e)/a,n[9]=(s+i)/l,n[10]=-(o+r)/A,n[11]=-1,n[12]=0,n[13]=0,n[14]=-o*r*2/A,n[15]=0,n},perspectiveMat4(e,t,i,s,r){const o=[],n=[];return o[2]=i,n[2]=s,n[1]=o[2]*Math.tan(e/2),o[1]=-n[1],n[0]=n[1]*t,o[0]=-n[0],d.frustumMat4v(o,n,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,n,a,l;const A=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],f=e[6],g=e[7],m=e[8],_=e[9],v=e[10],b=e[11],y=e[12],B=e[13],w=e[14],x=e[15];let P;for(let e=0;e{const e=new l(16),t=new l(16),i=new l(16);return function(s,r,o,n){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,n)}})(),lerpVec3(e,t,i,s,r,o){const n=o||d.vec3(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n},lerpMat4(e,t,i,s,r,o){const n=o||d.mat4(),a=(e-t)/(i-t);return n[0]=s[0]+a*(r[0]-s[0]),n[1]=s[1]+a*(r[1]-s[1]),n[2]=s[2]+a*(r[2]-s[2]),n[3]=s[3]+a*(r[3]-s[3]),n[4]=s[4]+a*(r[4]-s[4]),n[5]=s[5]+a*(r[5]-s[5]),n[6]=s[6]+a*(r[6]-s[6]),n[7]=s[7]+a*(r[7]-s[7]),n[8]=s[8]+a*(r[8]-s[8]),n[9]=s[9]+a*(r[9]-s[9]),n[10]=s[10]+a*(r[10]-s[10]),n[11]=s[11]+a*(r[11]-s[11]),n[12]=s[12]+a*(r[12]-s[12]),n[13]=s[13]+a*(r[13]-s[13]),n[14]=s[14]+a*(r[14]-s[14]),n[15]=s[15]+a*(r[15]-s[15]),n},flatten(e){const t=[];let i,s,r,o,n;for(i=0,s=e.length;i(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,o=e[2]*d.DEGTORAD/2,n=Math.cos(s),a=Math.cos(r),l=Math.cos(o),A=Math.sin(s),h=Math.sin(r),c=Math.sin(o);return"XYZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"YXZ"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"ZXY"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l-A*h*c):"ZYX"===t?(i[0]=A*a*l-n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l+A*h*c):"YZX"===t?(i[0]=A*a*l+n*h*c,i[1]=n*h*l+A*a*c,i[2]=n*a*c-A*h*l,i[3]=n*a*l-A*h*c):"XZY"===t&&(i[0]=A*a*l-n*h*c,i[1]=n*h*l-A*a*c,i[2]=n*a*c+A*h*l,i[3]=n*a*l+A*h*c),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],n=e[5],a=e[9],l=e[2],A=e[6],h=e[10];let c;const u=i+n+h;return u>0?(c=.5/Math.sqrt(u+1),t[3]=.25/c,t[0]=(A-a)*c,t[1]=(r-l)*c,t[2]=(o-s)*c):i>n&&i>h?(c=2*Math.sqrt(1+i-n-h),t[3]=(A-a)/c,t[0]=.25*c,t[1]=(s+o)/c,t[2]=(r+l)/c):n>h?(c=2*Math.sqrt(1+n-i-h),t[3]=(r-l)/c,t[0]=(s+o)/c,t[1]=.25*c,t[2]=(a+A)/c):(c=2*Math.sqrt(1+h-i-n),t[3]=(o-s)/c,t[0]=(r+l)/c,t[1]=(a+A)/c,t[2]=.25*c),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new l(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],o=e[2],n=e[3],a=t[0],l=t[1],A=t[2],h=t[3];return i[0]=n*a+s*h+r*A-o*l,i[1]=n*l+r*h+o*a-s*A,i[2]=n*A+o*h+s*l-r*a,i[3]=n*h-s*a-r*l-o*A,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],o=t[2],n=e[0],a=e[1],l=e[2],A=e[3],h=A*s+a*o-l*r,c=A*r+l*s-n*o,u=A*o+n*r-a*s,p=-n*s-a*r-l*o;return i[0]=h*A+p*-n+c*-l-u*-a,i[1]=c*A+p*-a+u*-n-h*-l,i[2]=u*A+p*-l+h*-a-c*-n,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],n=2*i,a=2*s,l=2*r,A=n*o,h=a*o,c=l*o,u=n*i,p=a*i,f=l*i,g=a*s,m=l*s,_=l*r;return t[0]=1-(g+_),t[1]=p+c,t[2]=f-h,t[4]=p-c,t[5]=1-(u+_),t[6]=m+A,t[8]=f+h,t[9]=m-A,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],n=i+i,a=s+s,l=r+r,A=i*n,h=i*a,c=i*l,u=s*a,d=s*l,p=r*l,f=o*n,g=o*a,m=o*l;return t[0]=1-(u+p),t[4]=h-m,t[8]=c+g,t[1]=h+m,t[5]=1-(A+p),t[9]=d-f,t[2]=c-g,t[6]=d+f,t[10]=1-(A+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new l(e||6),AABB2:e=>new l(e||4),OBB3:e=>new l(e||32),OBB2:e=>new l(e||16),Sphere3:(e,t,i,s)=>new l([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,n,a;const l=e[0],A=e[1],h=e[2],c=e[3],u=e[4],d=e[5],p=e[6],f=e[7],g=e[8],m=e[9],_=e[10],v=e[11],b=e[12],y=e[13],B=e[14],w=e[15];for(s=0;s{const e=new l(3),t=new l(3),i=new l(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=d.subVec3(t,e,i),n=r[0]-s[0],a=s[3]-r[0],l=r[1]-s[1],A=s[4]-r[1],h=r[2]-s[2],c=s[5]-r[2];return o[0]+=n>a?n:a,o[1]+=l>A?l:A,o[2]+=h>c?h:c,Math.abs(d.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new l(3);return(t,i,s)=>{i=i||d.AABB3();let r,o,n,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,A=d.MAX_DOUBLE,h=d.MIN_DOUBLE,c=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,p=t.length;ih&&(h=r),o>c&&(c=o),n>u&&(u=n);return i[0]=a,i[1]=l,i[2]=A,i[3]=h,i[4]=c,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,o=d.MAX_DOUBLE,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE,h=d.MIN_DOUBLE;for(let t=0,c=e.length;tl&&(l=i),s>A&&(A=s),r>h&&(h=r);return t[0]=o,t[1]=n,t[2]=a,t[3]=l,t[4]=A,t[5]=h,t},points3ToSphere3:(()=>{const e=new l(3);return(t,i)=>{i=i||d.vec4();let s,r=0,o=0,n=0;const a=t.length;for(s=0;sA&&(A=l);return i[3]=A,i}})(),positions3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length;let A=0;for(r=0;rA&&(A=c);return s[3]=A,s}})(),OBB3ToSphere3:(()=>{const e=new l(3),t=new l(3);return(i,s)=>{s=s||d.vec4();let r,o=0,n=0,a=0;const l=i.length,A=l/4;for(r=0;rc&&(c=h);return s[3]=c,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var o=0,n=e.length;o(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3](e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,o,n=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MIN_DOUBLE,A=d.MIN_DOUBLE;for(let t=0,h=e.length;tl&&(l=i),s>A&&(A=s);return t[0]=n,t[1]=a,t[2]=l,t[3]=A,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2](e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),n=.5*(s-t),a=r*r;return(2*t-2*i+o+n)*(r*a)+(-3*t+3*i-2*o-n)*a+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],o=t[1]-e[1],n=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],A=i[2]-e[2],h=o*A-n*l,c=n*a-r*A,u=r*l-o*a,p=Math.sqrt(h*h+c*c+u*u);return 0===p?(s[0]=0,s[1]=0,s[2]=0):(s[0]=h/p,s[1]=c/p,s[2]=u/p),s},rayTriangleIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3);return(o,n,a,l,A,h)=>{h=h||d.vec3();const c=d.subVec3(l,a,e),u=d.subVec3(A,a,t),p=d.cross3Vec3(n,u,i),f=d.dotVec3(c,p);if(f<1e-6)return null;const g=d.subVec3(o,a,s),m=d.dotVec3(g,p);if(m<0||m>f)return null;const _=d.cross3Vec3(g,c,r),v=d.dotVec3(n,_);if(v<0||m+v>f)return null;const b=d.dotVec3(u,_)/f;return h[0]=o[0]+b*n[0],h[1]=o[1]+b*n[1],h[2]=o[2]+b*n[2],h}})(),rayPlaneIntersect:(()=>{const e=new l(3),t=new l(3),i=new l(3),s=new l(3);return(r,o,n,a,l,A)=>{A=A||d.vec3(),o=d.normalizeVec3(o,e);const h=d.subVec3(a,n,t),c=d.subVec3(l,n,i),u=d.cross3Vec3(h,c,s);d.normalizeVec3(u,u);const p=-d.dotVec3(n,u),f=-(d.dotVec3(r,u)+p)/d.dotVec3(o,u);return A[0]=r[0]+f*o[0],A[1]=r[1]+f*o[1],A[2]=r[2]+f*o[2],A}})(),cartesianToBarycentric:(()=>{const e=new l(3),t=new l(3),i=new l(3);return(s,r,o,n,a)=>{const l=d.subVec3(n,r,e),A=d.subVec3(o,r,t),h=d.subVec3(s,r,i),c=d.dotVec3(l,l),u=d.dotVec3(l,A),p=d.dotVec3(l,h),f=d.dotVec3(A,A),g=d.dotVec3(A,h),m=c*f-u*u;if(0===m)return null;const _=1/m,v=(f*p-u*g)*_,b=(c*g-u*p)*_;return a[0]=1-v-b,a[1]=b,a[2]=v,a}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const o=e[0],n=e[1],a=e[2];return r[0]=t[0]*o+i[0]*n+s[0]*a,r[1]=t[1]*o+i[1]*n+s[1]*a,r[2]=t[2]*o+i[2]*n+s[2]*a,r},mergeVertices(e,t,i,s){const r={},o=[],n=[],a=t?[]:null,l=i?[]:null,A=[];let h,c,u,d;const p=1e4;let f,g,m=0;for(f=0,g=e.length;f{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3);return(n,a,l)=>{let A,h;const c=new Array(n.length/3);let u,p,f,g,m,_,v;for(A=0,h=a.length;A{const e=new l(3),t=new l(3),i=new l(3),s=new l(3),r=new l(3),o=new l(3),n=new l(3);return(a,l,A)=>{const h=new Float32Array(a.length);for(let c=0;c>24&255,h=u>>16&255,A=u>>8&255,l=255&u,a=t[i],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+1],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,a=t[i+2],n=3*a,r[d++]=e[n],r[d++]=e[n+1],r[d++]=e[n+2],o[p++]=l,o[p++]=A,o[p++]=h,o[p++]=c,u++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],n={};let a,l,A,h,c;const u=1e4;let p,f,g,m,_,v;for(f=0,m=e.length;f{const e=new l(4),t=new l(4);return(i,s,r,o,n)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),o[0]=t[0],o[1]=t[1],o[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),n[0]=t[0],n[1]=t[1],n[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new l(16),t=new l(16),i=new l(4),s=new l(4),r=new l(4),o=new l(4);return(n,a,l,A,h,c)=>{const u=d.mulMat4(l,a,e),p=d.inverseMat4(u,t),f=n.width,g=n.height,m=(A[0]-f/2)/(f/2),_=-(A[1]-g/2)/(g/2);i[0]=m,i[1]=_,i[2]=-1,i[3]=1,d.transformVec4(p,i,s),d.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=_,r[2]=1,r[3]=1,d.transformVec4(p,r,o),d.mulVec4Scalar(o,1/o[3]),h[0]=o[0],h[1]=o[1],h[2]=o[2],d.subVec3(o,s,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new l(3),t=new l(3);return(i,s,r,o,n,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,e,t),d.worldRayToLocalRay(o,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new l(16),t=new l(4),i=new l(4);return(s,r,o,n,a)=>{const l=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(l,t,i),n[0]=i[0],n[1]=i[1],n[2]=i[2],d.transformVec3(l,o,a)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const n=new l(6),a={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:n};let A,h;for(n[0]=n[1]=n[2]=Number.POSITIVE_INFINITY,n[3]=n[4]=n[5]=Number.NEGATIVE_INFINITY,A=0,h=i.length;An[3]&&(n[3]=r[t]),r[t+1]n[4]&&(n[4]=r[t+1]),r[t+2]n[5]&&(n[5]=r[t+2])}}if(i.length<20||o>10)return a.triangles=i,a.leaf=!0,a;e[0]=n[3]-n[0],e[1]=n[4]-n[1],e[2]=n[5]-n[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),a.splitDim=u;const d=(n[u]+n[u+3])/2,p=new Array(i.length);let f=0;const g=new Array(i.length);let m=0;for(A=0,h=i.length;A{const s=e.length/3,r=new Array(s);for(let e=0;e=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[F.index1],L=i[F.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,o=i.length;r{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;p[0]=r[3]-r[0],p[1]=r[4]-r[1],p[2]=r[5]-r[2];let o=0;if(p[1]>p[o]&&(o=1),p[2]>p[o]&&(o=2),!e.left){const n=r.slice();if(n[o+3]=(r[o]+r[o+3])/2,e.left={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const n=r.slice();if(n[o]=(r[o]+r[o+3])/2,e.right={aabb:n},d.containsAABB3(n,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var o=r[3];o=window.decodeURIComponent(o),e&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var n=0;n{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:b,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return y.isString(e)||y.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(y.isNumeric(e)||y.isString(e)?`${e}`:e.id)===(y.isNumeric(t)||y.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return y.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return y.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r{w.removeItem(e.id),delete I.scenes[e.id],delete B[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){x.push(e),x.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;x.length>0&&(e<0||s0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}for(let e in I.scenes)I.scenes[e].compile();T(e),E=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{D()}),100);const S=function(){let e=Date.now();if(M=e-E,E>0&&M>0){var t=1e3/M;F+=t,C.push(t),C.length>=30&&(F-=C.shift()),m.frame.fps=Math.round(F/C.length)}T(e),function(e){for(var t in P.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];P.sceneId=t,P.startTime=i.startTime,P.deltaTime=null!=P.prevTime?P.time-P.prevTime:0,i.fire("tick",P,!0)}P.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,o,n;for(n in e)e.hasOwnProperty(n)&&(i=e[n],s=B[n],s||(s=B[n]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),o=i.ticksPerRender,s.ticksPerRender!==o&&(s.ticksPerRender=o,s.renderCountdown=o),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=o))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(D):requestAnimationFrame(S)};function T(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}S();class L{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof L))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+y.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,n=e.on,a=!1!==e.recompiles;if(i&&(y.isNumeric(i)||y.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+y.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+y.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+y.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let A,h,c;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(A=e.subs,h=0,c=A.length;h{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class N{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function Q(e,t,i){const s=d.mulMat4(i,t,k),r=s[0],o=s[1],n=s[2],a=s[3],l=s[4],A=s[5],h=s[6],c=s[7],u=s[8],p=s[9],f=s[10],g=s[11],m=s[12],_=s[13],v=s[14],b=s[15];e.planes[0].set(a-r,c-l,g-u,b-m),e.planes[1].set(a+r,c+l,g+u,b+m),e.planes[2].set(a-o,c-A,g-p,b-_),e.planes[3].set(a+o,c+A,g+p,b+_),e.planes[4].set(a-n,c-h,g-f,b-v),e.planes[5].set(a+n,c+h,g+f,b+v)}function V(e,t){let i=N.INSIDE;const s=R,r=U;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const o=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*o[s.testVertex[0]][0]+s.normal[1]*o[s.testVertex[1]][1]+s.normal[2]*o[s.testVertex[2]][2]+s.offset<0)return N.OUTSIDE;s.normal[0]*o[1-s.testVertex[0]][0]+s.normal[1]*o[1-s.testVertex[1]][1]+s.normal[2]*o[1-s.testVertex[2]][2]+s.offset<0&&(i=N.INTERSECT)}return i}N.INSIDE=0,N.INTERSECT=1,N.OUTSIDE=2;class H extends L{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new N,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==H.PICK_MODE_INSIDE&&e!==H.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===H.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=N.INTERSECT)=>{if(s===N.INTERSECT&&(s=V(this._marqueeFrustum,i.aabb)),s!==N.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,o=2/t,n=2/i,a=e.clientHeight/e.clientWidth,l=(this._canvasMarquee[0]-s)*o-1,A=(this._canvasMarquee[2]-s)*o-1,h=-(this._canvasMarquee[3]-r)*n+1,c=-(this._canvasMarquee[1]-r)*n+1,u=this.viewer.scene.camera.frustum.near*(17*a);d.frustumMat4(l,A,h*a,c*a,u,1e4,this._marqueeFrustumProjMat),Q(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}H.PICK_MODE_INTERSECTS=0,H.PICK_MODE_INSIDE=1;class j extends L{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,o,n,a,l,A,h=!1,c=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(A=setTimeout((function(){const o=t.viewer.scene.input;o.keyDown[o.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,a=e.offsetX,t.setMarqueeCorner1([s,r]),h=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),c=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!h&&!u)return;if(0!==e.button)return;clearTimeout(A),o=e.pageX,n=e.pageY;const i=Math.abs(o-s),a=Math.abs(n-r);h=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||a>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(A),h&&(t.setMarqueeVisible(!1),h=!1,c=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&c&&(clearTimeout(A),h&&(o=e.pageX,n=e.pageY,l=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([o,n]),t.setPickMode(a{if(!this._running)return;i||(i=e);const r=e-i,o=Math.min(r/300,1),n=t+(2-t)*o;this._circleRadius=n,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",o<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}class z{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const n=this._events[t];return void 0!==n&&i.call(s||this,n),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const W=d.vec3(),K=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o){return o=o||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,o),o.slice()}}();function X(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],n=e[1]-o,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=o,t[2]=a,i[0]=r,i[1]=n,i[2]=l}function Y(e,t,i,s=1e3){const r=d.getPositionsCenter(e,W),o=Math.round(r[0]/s)*s,n=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=o,i[1]=n,i[2]=a;const l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(let i=0,s=e.length;i0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){he.set(this._viewPos),he[3]=1,d.transformPoint4(this.scene.camera.projMatrix,he,ce);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+ce[0]/ce[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-ce[1]/ce[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){if(this._entity){if(this._entity===e)return;null!==this._onEntityDestroyed&&(this._entity.model.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null)}this._entity=e,this._entity&&(this._entity instanceof Ae?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0)}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),X(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._entity&&(null!==this._onEntityDestroyed&&this._entity.model.off(this._onEntityDestroyed),null!==this._onEntityModelDestroyed&&this._entity.model.off(this._onEntityModelDestroyed)),this._renderer.removeMarker(this),super.destroy()}}const de={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i}};class pe{constructor(e,t={}){this._color=t.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=t.thickness||1,this._thicknessClickable=t.thicknessClickable||6,this._visible=!0,this._culled=!1;var i=this._wire,s=i.style;s.border="solid "+this._thickness+"px "+this._color,s.position="absolute",s["z-index"]=void 0===t.zIndex?"2000001":t.zIndex,s.width="0px",s.height="0px",s.visibility="visible",s.top="0px",s.left="0px",s["-webkit-transform-origin"]="0 0",s["-moz-transform-origin"]="0 0",s["-ms-transform-origin"]="0 0",s["-o-transform-origin"]="0 0",s["transform-origin"]="0 0",s["-webkit-transform"]="rotate(0deg)",s["-moz-transform"]="rotate(0deg)",s["-ms-transform"]="rotate(0deg)",s["-o-transform"]="rotate(0deg)",s.transform="rotate(0deg)",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._wireClickable,o=r.style;o.border="solid "+this._thicknessClickable+"px "+this._color,o.position="absolute",o["z-index"]=void 0===t.zIndex?"2000002":t.zIndex+1,o.width="0px",o.height="0px",o.visibility="visible",o.top="0px",o.left="0px",o["-webkit-transform-origin"]="0 0",o["-moz-transform-origin"]="0 0",o["-ms-transform-origin"]="0 0",o["-o-transform-origin"]="0 0",o["transform-origin"]="0 0",o["-webkit-transform"]="rotate(0deg)",o["-moz-transform"]="rotate(0deg)",o["-ms-transform"]="rotate(0deg)",o["-o-transform"]="rotate(0deg)",o.transform="rotate(0deg)",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),t.onMouseOver&&r.addEventListener("mouseover",(e=>{t.onMouseOver(e,this)})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}get visible(){return"visible"===this._wire.style.visibility}_update(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}setStartAndEnd(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}setColor(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}setOpacity(e){this._wire.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}destroy(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}class fe{constructor(e,t={}){this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!t.visible,this._culled=!1;var i=this._dot,s=i.style;s["border-radius"]="25px",s.border="solid 2px white",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"40000005":t.zIndex,s.width="8px",s.height="8px",s.visibility=!1!==t.visible?"visible":"hidden",s.top="0px",s.left="0px",s["box-shadow"]="0 2px 5px 0 #182A3D;",s.opacity=1,s["pointer-events"]="none",t.onContextMenu,e.appendChild(i);var r=this._dotClickable,o=r.style;o["border-radius"]="35px",o.border="solid 10px white",o.position="absolute",o["z-index"]=void 0===t.zIndex?"40000007":t.zIndex+1,o.width="8px",o.height="8px",o.visibility="visible",o.top="0px",o.left="0px",o.opacity=0,o["pointer-events"]="none",t.onContextMenu,e.appendChild(r),r.addEventListener("click",(t=>{e.dispatchEvent(new MouseEvent("mouseover",t))})),t.onMouseOver&&r.addEventListener("mouseover",(i=>{t.onMouseOver(i,this),e.dispatchEvent(new MouseEvent("mouseover",i))})),t.onMouseLeave&&r.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this)})),t.onMouseWheel&&r.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&r.addEventListener("mousedown",(e=>{t.onMouseDown(e,this)})),t.onMouseUp&&r.addEventListener("mouseup",(e=>{t.onMouseUp(e,this)})),t.onMouseMove&&r.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(r.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),r.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):r.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),t.onTouchstart&&r.addEventListener("touchstart",(e=>{t.onTouchstart(e,this)})),t.onTouchmove&&r.addEventListener("touchmove",(e=>{t.onTouchmove(e,this)})),t.onTouchend&&r.addEventListener("touchend",(e=>{t.onTouchend(e,this)})),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.borderColor)}setPos(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}setFillColor(e){this._dot.style.background=e||"lightgreen"}setBorderColor(e){this._dot.style.border="solid 2px"+(e||"black")}setOpacity(e){this._dot.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setClickable(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}destroy(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}class ge{constructor(e,t={}){this._highlightClass="viewer-ruler-label-highlighted",this._prefix=t.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var i=this._label,s=i.style;s["border-radius"]="5px",s.color="white",s.padding="4px",s.border="solid 1px",s.background="lightgreen",s.position="absolute",s["z-index"]=void 0===t.zIndex?"5000005":t.zIndex,s.width="auto",s.height="auto",s.visibility="visible",s.top="0px",s.left="0px",s["pointer-events"]="all",s.opacity=1,t.onContextMenu,i.innerText="",e.appendChild(i),this.setPos(t.x||0,t.y||0),this.setFillColor(t.fillColor),this.setBorderColor(t.fillColor),this.setText(t.text),t.onMouseOver&&i.addEventListener("mouseover",(e=>{t.onMouseOver(e,this),e.preventDefault()})),t.onMouseLeave&&i.addEventListener("mouseleave",(e=>{t.onMouseLeave(e,this),e.preventDefault()})),t.onMouseWheel&&i.addEventListener("wheel",(e=>{t.onMouseWheel(e,this)})),t.onMouseDown&&i.addEventListener("mousedown",(e=>{t.onMouseDown(e,this),e.stopPropagation()})),t.onMouseUp&&i.addEventListener("mouseup",(e=>{t.onMouseUp(e,this),e.stopPropagation()})),t.onMouseMove&&i.addEventListener("mousemove",(e=>{t.onMouseMove(e,this)})),t.onContextMenu&&(de.isIphoneSafari()?(i.addEventListener("touchstart",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null),this._timeout=setTimeout((()=>{e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,t.onContextMenu(e,this),clearTimeout(this._timeout),this._timeout=null}),500)})),i.addEventListener("touchend",(e=>{e.preventDefault(),this._timeout&&(clearTimeout(this._timeout),this._timeout=null)}))):i.addEventListener("contextmenu",(e=>{console.log(e),t.onContextMenu(e,this),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}setPos(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}setPosOnWire(e,t,i,s){var r=e+.5*(i-e),o=t+.5*(s-t),n=this._label.style;n.left=Math.round(r)-20+"px",n.top=Math.round(o)-12+"px"}setPosBetweenWires(e,t,i,s,r,o){var n=(e+i+r)/3,a=(t+s+o)/3,l=this._label.style;l.left=Math.round(n)-20+"px",l.top=Math.round(a)-12+"px"}setText(e){this._label.innerHTML=this._prefix+(e||"")}setFillColor(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}setBorderColor(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}setOpacity(e){this._label.style.opacity=e}setVisible(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setCulled(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}setHighlighted(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}setClickable(e){this._label.style["pointer-events"]=e?"all":"none"}setPrefix(e){this._prefix!==e&&(this._prefix=e)}destroy(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}var me=d.vec3(),_e=d.vec3();class ve extends L{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._color=t.color||e.defaultColor;var i=this.plugin.viewer.scene;this._originMarker=new ue(i,t.origin),this._cornerMarker=new ue(i,t.corner),this._targetMarker=new ue(i,t.target),this._originWorld=d.vec3(),this._cornerWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(12),this._vp=new Float64Array(12),this._pp=new Float64Array(12),this._cp=new Int16Array(6);const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},l=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};this._originDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._cornerDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._originWire=new pe(this._container,{color:this._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._targetWire=new pe(this._container,{color:this._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._angleLabel=new ge(this._container,{fillColor:this._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:s,onMouseLeave:r,onMouseWheel:n,onMouseDown:a,onMouseUp:l,onMouseMove:A,onContextMenu:o}),this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._visible=!1,this._originVisible=!1,this._cornerVisible=!1,this._targetVisible=!1,this._originWireVisible=!1,this._targetWireVisible=!1,this._angleVisible=!1,this._labelsVisible=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._cornerMarker.on("worldPos",(e=>{this._cornerWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.cornerVisible=t.cornerVisible,this.targetVisible=t.targetVisible,this.originWireVisible=t.originWireVisible,this.targetWireVisible=t.targetWireVisible,this.angleVisible=t.angleVisible,this.labelsVisible=t.labelsVisible}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){const u=-.3,p=this._originMarker.viewPos[2],f=this._cornerMarker.viewPos[2],g=this._targetMarker.viewPos[2];if(p>u||f>u||g>u)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var t=this._pp,i=this._cp,s=e.canvas.canvas.getBoundingClientRect();const m=this._container.getBoundingClientRect();for(var r=s.top-m.top,o=s.left-m.left,n=e.canvas.boundary,a=n[2],l=n[3],A=0,h=0,c=t.length;he.offsetTop+(e.offsetParent&&e.offsetParent!==t.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==t.parentNode&&c(e.offsetParent)),u=d.vec2();this._onMouseHoverSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{e.snappedToVertex||e.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!0),this.markerDiv.style.background="greenyellow",this.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=e.canvasPos,s.snappedCanvasPos=e.canvasPos,s.snapped=!1),this.markerDiv.style.background="pink",this.markerDiv.style.border="2px solid red");const i=e.snappedCanvasPos||e.canvasPos;switch(r=!0,o=e.entity,l.set(e.worldPos),A.set(i),this._mouseState){case 0:this._canvasToPagePos?(this._canvasToPagePos(t,i,u),this.markerDiv.style.left=u[0]-5+"px",this.markerDiv.style.top=u[1]-5+"px"):(this.markerDiv.style.left=c(t)+i[0]-5+"px",this.markerDiv.style.top=h(t)+i[1]-5+"px");break;case 1:this._currentAngleMeasurement&&(this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.angleVisible=!1,this._currentAngleMeasurement.corner.worldPos=e.worldPos,this._currentAngleMeasurement.corner.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer";break;case 2:this._currentAngleMeasurement&&(this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.angleVisible=!0,this._currentAngleMeasurement.target.worldPos=e.worldPos,this._currentAngleMeasurement.target.entity=e.entity),this.markerDiv.style.left="-10000px",this.markerDiv.style.top="-10000px",t.style.cursor="pointer"}})),t.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(n=e.clientX,a=e.clientY)}),t.addEventListener("mouseup",this._onMouseUp=e=>{if(1===e.which&&!(e.clientX>n+20||e.clientXa+20||e.clientY{if(r=!1,s&&(s.visible=!0,s.pointerPos=e.canvasPos,s.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,s.snapped=!1),this.markerDiv.style.left="-100px",this.markerDiv.style.top="-100px",this._currentAngleMeasurement){switch(this._mouseState){case 0:this._currentAngleMeasurement.originVisible=!1;break;case 1:this._currentAngleMeasurement.cornerVisible=!1,this._currentAngleMeasurement.originWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1;break;case 2:this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1}t.style.cursor="default"}})),this._active=!0}deactivate(){if(!this._active)return;this.pointerLens&&(this.pointerLens.visible=!1),this.markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.angleMeasurementsPlugin.viewer.cameraControl;t.off(this._onMouseHoverSurface),t.off(this._onPickedSurface),t.off(this._onHoverNothing),t.off(this._onPickedNothing),this._currentAngleMeasurement=null,this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentAngleMeasurement}destroy(){this.deactivate(),super.destroy()}}class Be extends z{constructor(e,t={}){super("AngleMeasurements",e),this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.zIndex=t.zIndex||1e4,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,angleMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,angleMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get control(){return this._defaultControl||(this._defaultControl=new ye(this,{})),this._defaultControl}get measurements(){return this._measurements}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.corner,s=e.target,r=new ve(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},corner:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:e.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.on("destroyed",(()=>{delete this._measurements[r.id]})),r.clickable=!0,this.fire("measurementCreated",r),r}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentAngleMeasurement&&(this._currentAngleMeasurement.destroy(),this._currentAngleMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const i=e.touches.length;if(1!==i||1!==e.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const r=e.touches[0],n=r.clientX,l=r.clientY;if(r.identifier!==A)return;let h,c;switch(a.set([n,l]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(h.worldPos),this._currentAngleMeasurement.origin.worldPos=h.worldPos):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),s.set(c.worldPos),this._currentAngleMeasurement.origin.worldPos=c.worldPos):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.corner.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.corner.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!1,this._currentAngleMeasurement.targetVisible=!1,this._currentAngleMeasurement.targetWireVisible=!1,this._currentAngleMeasurement.angleVisible=!1)),this._touchState=5;break;case 8:if(1!==i&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),h=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),h&&h.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=h.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentAngleMeasurement.target.worldPos=h.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0):(c=t.pick({canvasPos:a,pickSurface:!0}),c&&c.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=c.canvasPos,this.pointerLens.snapped=!1),this._currentAngleMeasurement.target.worldPos=c.worldPos,this._currentAngleMeasurement.originVisible=!0,this._currentAngleMeasurement.originWireVisible=!0,this._currentAngleMeasurement.cornerVisible=!0,this._currentAngleMeasurement.cornerWireVisible=!0,this._currentAngleMeasurement.targetVisible=!0,this._currentAngleMeasurement.targetWireVisible=!0,this._currentAngleMeasurement.angleVisible=!0)),this._touchState=8}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{this.plugin.fire("markerClicked",this)}),this._marker.addEventListener("mouseenter",this._onMouseEnterExternalMarker=()=>{this.plugin.fire("markerMouseEnter",this)}),this._marker.addEventListener("mouseleave",this._onMouseLeaveExternalMarker=()=>{this.plugin.fire("markerMouseLeave",this)}),this._markerExternal=!0):(this._markerHTML=t.markerHTML,this._htmlDirty=!0,this._markerExternal=!1),t.labelElement?(this._label=t.labelElement,this._labelExternal=!0):(this._labelHTML=t.labelHTML,this._htmlDirty=!0,this._labelExternal=!1),this._markerShown=!!t.markerShown,this._labelShown=!!t.labelShown,this._values=t.values||{},this._layoutDirty=!0,this._visibilityDirty=!0,this._buildHTML(),this._onTick=this.scene.on("tick",(()=>{this._htmlDirty&&(this._buildHTML(),this._htmlDirty=!1,this._layoutDirty=!0,this._visibilityDirty=!0),(this._layoutDirty||this._visibilityDirty)&&(this._markerShown||this._labelShown)&&(this._updatePosition(),this._layoutDirty=!1),this._visibilityDirty&&(this._marker.style.visibility=this.visible&&this._markerShown?"visible":"hidden",this._label.style.visibility=this.visible&&this._markerShown&&this._labelShown?"visible":"hidden",this._visibilityDirty=!1)})),this.on("canvasPos",(()=>{this._layoutDirty=!0})),this.on("visible",(()=>{this._visibilityDirty=!0})),this.setMarkerShown(!1!==t.markerShown),this.setLabelShown(t.labelShown),this.eye=t.eye?t.eye.slice():null,this.look=t.look?t.look.slice():null,this.up=t.up?t.up.slice():null,this.projection=t.projection}_buildHTML(){if(!this._markerExternal){this._marker&&(this._container.removeChild(this._marker),this._marker=null);let e=this._markerHTML||"

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

";y.isArray(e)&&(e=e.join("")),e=this._renderTemplate(e.trim());const t=document.createRange().createContextualFragment(e);this._label=t.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))}))}}_updatePosition(){const e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}_renderTemplate(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){const i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}setMarkerShown(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}getMarkerShown(){return this._markerShown}setLabelShown(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}getLabelShown(){return this._labelShown}setField(e,t){this._values[e]=t||"",this._htmlDirty=!0}getField(e){return this._values[e]}setValues(e){for(var t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setField(t,i)}}getValues(){return this._values}destroy(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),super.destroy()}}const Pe=d.vec3(),Ce=d.vec3(),Me=d.vec3();class Ee extends z{constructor(e,t){super("Annotations",e),this._labelHTML=t.labelHTML||"
",this._markerHTML=t.markerHTML||"
",this._container=t.container||document.body,this._values=t.values||{},this.annotations={},this.surfaceOffset=t.surfaceOffset}getContainerElement(){return this._container}send(e,t){if("clearAnnotations"===e)this.clear()}set surfaceOffset(e){null==e&&(e=.3),this._surfaceOffset=e}get surfaceOffset(){return this._surfaceOffset}createAnnotation(e){var t,i;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){const s=e.pickResult;if(s.worldPos&&s.worldNormal){const e=d.normalizeVec3(s.worldNormal,Pe),r=d.mulVec3Scalar(e,this._surfaceOffset,Ce);t=d.addVec3(s.worldPos,r,Me),i=s.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var s=null;e.markerElementId&&((s=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var r=null;e.labelElementId&&((r=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));const o=new xe(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:s,labelElement:r,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:y.apply(e.values,y.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[o.id]=o,o.on("destroyed",(()=>{delete this.annotations[o.id],this.fire("annotationDestroyed",o.id)})),this.fire("annotationCreated",o.id),o}destroyAnnotation(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}clear(){const e=Object.keys(this.annotations);for(var t=0,i=e.length;t
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const Ie=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class De extends L{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new Fe(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e0?Te.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?Te.FS_MAX_FLOAT_PRECISION="mediump":Te.FS_MAX_FLOAT_PRECISION="lowp":Te.FS_MAX_FLOAT_PRECISION="mediump",Te.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),Te.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),Te.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),Te.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),Te.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Te.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),Te.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),Te.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),Te.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),Te.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){Te.SUPPORTED_EXTENSIONS[e]=!0})))}class Re{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}class Ue{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function Ve(e){console.error(e.join("\n"))}class He{constructor(e,t){this.id=Ne.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Ue(e,e.VERTEX_SHADER,Qe(this.source.vertex)),this._fragmentShader=new Ue(e,e.FRAGMENT_SHADER,Qe(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void Ve(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void Ve(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void Ve(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void Ve(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void Ve(this.errors);const n=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class Ge{constructor(e,t){this.scene=e,this.aabb=d.AABB3(),this.origin=d.vec3(t),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t-t){i._setVisible(!1);continue}const n=i.canvasPos,a=n[0],l=n[1];a+10<0||l+10<0||a-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=a,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i||(i=new Ge(this._scene,e.origin),this._occlusionLayers[i.originHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return;const i=e.origin.join();if(i!==t.originHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.originHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new Ge(this._scene,e.origin),this._occlusionLayers[i]=s,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.origin.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.originHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new He(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e0){const e=s.sectionPlanes;for(let s=0;s{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,n=t.drawingBufferHeight,a=s.camera.project._state,l=a.near,A=a.far,h=a.matrix,c=this._getInverseProjectMat(),u=Math.random(),p="perspective"===s.camera.projection;Xe[0]=o,Xe[1]=n,t.viewport(0,0,o,n),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,A),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,h),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,c),t.uniform1i(this._uPerspective,p),t.uniform1f(this._uScale,r.scale*(A/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,Xe),t.uniform1f(this._uRandomSeed,u);const f=e.getDepthTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new He(i,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV; \n \n out vec2 vUV;\n \n void main () {\n gl_Position = vec4(aPosition, 1.0);\n vUV = aUV;\n }"],fragment:[`#version 300 es \n precision highp float;\n precision highp int; \n \n #define NORMAL_TEXTURE 0\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n #define NUM_SAMPLES ${this._numSamples}\n #define NUM_RINGS 4 \n \n in vec2 vUV;\n \n uniform sampler2D uDepthTexture;\n \n uniform float uCameraNear;\n uniform float uCameraFar;\n uniform mat4 uProjectMatrix;\n uniform mat4 uInverseProjectMatrix;\n \n uniform bool uPerspective;\n\n uniform float uScale;\n uniform float uIntensity;\n uniform float uBias;\n uniform float uKernelRadius;\n uniform float uMinResolution;\n uniform vec2 uViewport;\n uniform float uRandomSeed;\n\n float pow2( const in float x ) { return x*x; }\n \n highp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n }\n\n vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n }\n\n vec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 2.0 * rgb.xyz - 1.0;\n }\n\n const float packUpscale = 256. / 255.;\n const float unpackDownScale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. ); \n\n const float shiftRights = 1. / 256.;\n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float unpackRGBAToFloat( const in vec4 v ) { \n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n }\n\n float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n }\n \n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n if (uPerspective) {\n return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n } else {\n return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n }\n }\n\n vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n \tclipPosition *= clipW; \n \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n }\n\n vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) { \n return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n }\n\n float scaleDividedByCameraFar;\n float minResolutionMultipliedByCameraFar;\n\n float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n \tfloat viewDistance = length( viewDelta );\n \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n }\n\n const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n \n \tscaleDividedByCameraFar = uScale / uCameraFar;\n \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n \tvec2 radiusStep = radius;\n\n \tfloat occlusionSum = 0.0;\n \tfloat weightSum = 0.0;\n\n \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n \t\tradius += radiusStep;\n \t\tangle += ANGLE_STEP;\n\n \t\tfloat sampleDepth = getDepth( sampleUv );\n \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }`]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new je(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new je(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new je(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const Je=new Float32Array(it(17,[0,1])),Ze=new Float32Array(it(17,[1,0])),qe=new Float32Array(function(e,t){const i=[];for(let s=0;s<=e;s++)i.push(tt(s,t));return i}(17,4)),$e=new Float32Array(2);class et{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new He(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS 16\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new je(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new je(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new je(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=d.mat4();return()=>(e&&d.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,n=s.drawingBufferWidth,a=s.drawingBufferHeight,l=o.camera.project._state,A=l.near,h=l.far;s.viewport(0,0,n,a),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),$e[0]=n,$e[1]=a,s.uniform2fv(this._uViewport,$e),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,h),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Ze):s.uniform2fv(this._uSampleOffsets,Je),s.uniform1fv(this._uSampleWeights,qe);const c=e.getDepthTexture(),u=t.getTexture();r.bindTexture(this._uDepthTexture,c,0),r.bindTexture(this._uOcclusionTexture,u,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function tt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function it(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}class st{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(...e){if(this._touch(...e),this.bound)return;const t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}createTexture(e,t,i=null){const s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}_touch(...e){let t,i;const s=this.gl;if(this.size?(t=this.size[0],i=this.size[1]):(t=s.drawingBufferWidth,i=s.drawingBufferHeight),this.buffer){if(this.buffer.width===t&&this.buffer.height===i)return;this.buffer.textures.forEach((e=>s.deleteTexture(e))),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}const r=[];let o;e.length>0?r.push(...e.map((e=>this.createTexture(t,i,e)))):r.push(this.createTexture(t,i)),this._hasDepthTexture&&(o=s.createTexture(),s.bindTexture(s.TEXTURE_2D,o),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,t,i,0,s.DEPTH_COMPONENT,s.FLOAT,null));const n=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,n),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,t,i);const a=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,a);for(let e=0;e0&&s.drawBuffers(r.map(((e,t)=>s.COLOR_ATTACHMENT0+t))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,o,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,n),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,a),!s.isFramebuffer(a))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={framebuf:a,renderbuf:n,texture:r[0],textures:r,depthTexture:o,width:t,height:i},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t,i=null,s=null,r=Uint8Array,o=4,n=0){const a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,A=new r(o),h=this.gl;return h.readBuffer(h.COLOR_ATTACHMENT0+n),h.readPixels(a,l,1,1,i||h.RGBA,s||h.UNSIGNED_BYTE,A,0),A}readArray(e=null,t=null,i=Uint8Array,s=4,r=0){const o=new i(this.buffer.width*this.buffer.height*s),n=this.gl;return n.readBuffer(n.COLOR_ATTACHMENT0+r),n.readPixels(0,0,this.buffer.width,this.buffer.height,e||n.RGBA,t||n.UNSIGNED_BYTE,o,0),o}readImageAsCanvas(){const e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,o=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);const n=this.buffer.width,a=this.buffer.height,l=a/2|0,A=4*n,h=new Uint8Array(4*n);for(let e=0;ee.deleteTexture(t))),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class rt{constructor(e){this.scene=e,this._renderBuffersBasic={},this._renderBuffersScaled={}}getRenderBuffer(e,t){const i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled;let s=i[e];return s||(s=new st(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}destroy(){for(let e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(let e in this._renderBuffersScaled)this._renderBuffersScaled[e].destroy()}}function ot(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}const nt=function(t,i){i=i||{};const s=new Se(t),r=t.canvas.canvas,o=t.canvas.gl,n=!!i.transparent,a=i.alphaDepthMask,l=new e({});let A={},h={},c=[],u=[],p=!0,f=!0,g=!0,_=!0,v=!0,b=!0,y=!0,B=!0;const w=new rt(t);let x=!1;const P=new Ye(t),C=new et(t);function M(){p&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),p=!1,f=!0),f&&(!function(){for(let e in A)if(A.hasOwnProperty(e)){const t=A[e];t.isStateSortable&&(t.drawableListPreCull.sort(t.stateSortCompare),t.drawableList=t.drawableListPreCull)}let e=0;for(let t in A)if(A.hasOwnProperty(t)){const i=A[t].drawableListPreCull;for(let t=0,s=i.length;te.renderOrder-t.renderOrder))}(),f=!1,g=!0),g&&function(){let e=0;for(let t=0,i=c.length;t0)for(s.withSAO=!0,S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||H>0||k>0||O>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,a||o.depthMask(!1),(k>0||O>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),O>0)for(S=0;S0)for(S=0;S0)for(S=0;S0)for(S=0;S0||G>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),G>0)for(S=0;S0)for(S=0;S0||W>0||j>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),o.enable(o.CULL_FACE),W>0)for(S=0;S0)for(S=0;S0||X>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),X>0)for(S=0;S0)for(S=0;S0||J>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),n?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),J>0)for(S=0;S0)for(S=0;S0){const t=Math.floor(e/4),i=u.size[0],s=t%i-Math.floor(i/2),r=Math.floor(t/i)-Math.floor(i/2),o=Math.sqrt(Math.pow(s,2)+Math.pow(r,2));M.push({x:s,y:r,dist:o,isVertex:n&&a?_[e+3]>m.length/2:n,result:[_[e+0],_[e+1],_[e+2],_[e+3]],normal:[v[e+0],v[e+1],v[e+2],v[e+3]],id:[b[e+0],b[e+1],b[e+2],b[e+3]]})}let E=null,F=null,T=null,L=null;if(M.length>0){M.sort(((e,t)=>e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist)),L=M[0].isVertex?"vertex":"edge";const e=M[0].result,t=M[0].normal,i=M[0].id,s=m[e[3]],r=s.origin,o=s.coordinateScale;F=d.normalizeVec3([t[0]/d.MAX_INT,t[1]/d.MAX_INT,t[2]/d.MAX_INT]),E=[e[0]*o[0]+r[0],e[1]*o[1]+r[1],e[2]*o[2]+r[2]],T=l.items[i[0]+(i[1]<<8)+(i[2]<<16)+(i[3]<<24)]}if(null===y&&null==E)return null;let R=null;null!==E&&(R=t.camera.projectWorldPos(E));const U=T&&T.delegatePickedEntity?T.delegatePickedEntity():T;return h.reset(),h.snappedToEdge="edge"===L,h.snappedToVertex="vertex"===L,h.worldPos=E,h.worldNormal=F,h.entity=U,h.canvasPos=i,h.snappedCanvasPos=R||i,h}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new Ke(t,w),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){M(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in A)if(A.hasOwnProperty(e)){const t=A[e].drawableList;for(let e=0,i=t.length;e{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const lt=new e({});class At{constructor(e){this.id=lt.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){lt.removeItem(this.id)}}class ht extends L{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new At({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class ct extends L{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class ut extends L{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],o=s/r;let n,a,l,A;s>r?(n=-t,a=t,l=t/o,A=-t/o):(n=-t*o,a=t*o,l=t,A=-t),d.orthoMat4c(n,a,A,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class dt extends L{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class pt extends L{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new At({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,n=o.offsetWidth/2,a=o.offsetHeight/2;return i[0]=(e[0]-n)/n,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ft=d.vec3(),gt=d.vec3(),mt=d.vec3(),_t=d.vec3(),vt=d.vec3(),bt=d.vec3(),yt=d.vec4(),Bt=d.vec4(),wt=d.vec4(),xt=d.mat4(),Pt=d.mat4(),Ct=d.vec3(),Mt=d.vec3(),Et=d.vec3(),Ft=d.vec3();class It extends L{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new At({deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new ct(this),this._ortho=new ut(this),this._frustum=new dt(this),this._customProjection=new pt(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(d.subVec3(this._eye,this._look,Ct),d.normalizeVec3(Ct,Mt),d.mulVec3Scalar(Mt,1e3,Et),d.addVec3(this._look,Et,Ft),t=Ft):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,Pt),d.mulMat4(e.deviceMatrix,Pt,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,ft);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,xt),t=d.transformPoint3(xt,t,gt),this.eye=d.addVec3(this._look,t,mt),this.up=d.transformPoint3(xt,this._up,_t)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ft);const i=d.cross3Vec3(d.normalizeVec3(t,gt),d.normalizeVec3(this._up,mt));d.rotationMat4v(.0174532925*e,i,xt),t=d.transformPoint3(xt,t,_t),this.up=d.transformPoint3(xt,this._up,vt),this.eye=d.addVec3(t,this._look,bt)}yaw(e){let t=d.subVec3(this._look,this._eye,ft);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,xt),t=d.transformPoint3(xt,t,gt),this.look=d.addVec3(t,this._eye,mt),this._gimbalLock&&(this.up=d.transformPoint3(xt,this._up,_t))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ft);const i=d.cross3Vec3(d.normalizeVec3(t,gt),d.normalizeVec3(this._up,mt));d.rotationMat4v(.0174532925*e,i,xt),this.up=d.transformPoint3(xt,this._up,bt),t=d.transformPoint3(xt,t,_t),this.look=d.addVec3(t,this._eye,vt)}pan(e){const t=d.subVec3(this._eye,this._look,ft),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,gt));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,mt),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,_t),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,vt),this.look=d.addVec3(this._look,i,bt)}zoom(e){const t=d.subVec3(this._eye,this._look,ft),i=Math.abs(d.lenVec3(t,gt)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,mt);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),_t)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,ft))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}projectWorldPos(e){const t=yt,i=Bt,s=wt;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,o=r.offsetWidth/2,n=r.offsetHeight/2;return[s[0]*o+o,s[1]*n+n]}destroy(){super.destroy(),this._state.destroy()}}class Dt extends L{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class St extends Dt{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new At({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new st(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Tt extends Dt{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Lt extends L{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}var Rt=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const n=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3();return function(m,_,v,b){!function(r,o){const n={};let a,l,A,h;const c=Math.pow(10,4);let u,d,p=0;for(u=0,d=r.length;uB)||(T=i[F.index1],L=i[F.index2],(!R&&T>65535||L>65535)&&(R=!0),y.push(T),y.push(L));return R?new Uint32Array(y):new Uint16Array(y)}}();const Ut=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],o=i[1],n=i[2],a=i[3]-r,l=i[4]-o,A=i[5]-n,h=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([a/h,l/h,A/h],t),d.mulMat4(e,t,s),s}}();var kt=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const o=new Uint16Array(i.length),n=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let a;for(a=0;a=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Qt(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Vt(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Ht={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;sn&&(r=i,n=o),i=Nt(e,a,"floor","ceil"),s=Qt(i),o=Vt(e,a,s),o>n&&(r=i,n=o),i=Nt(e,a,"ceil","ceil"),s=Qt(i),o=Vt(e,a,s),o>n&&(r=i,n=o),t[a]=r[0],t[a+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const a=Math.sqrt(r*r+o*o+n*n);t[s+0]=r/a,t[s+1]=o/a,t[s+2]=n/a,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},jt=m.memory,Gt=d.AABB3();class zt extends Lt{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new At({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Ht.getPositionsBounds(t.positions),s=Ht.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Ht.getUVBounds(t.uv),s=Ht.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);t.normals&&(this._state.compressGeometry?i.normals=Ht.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),jt.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),jt.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new je(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),jt.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new je(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),jt.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new je(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),jt.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new je(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),jt.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=Rt(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),jt.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new je(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),jt.positions+=this._pickTrianglePositionsBuf.numItems,jt.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Ht.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Ht.getPositionsBounds(e),s=Ht.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Ht.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Ht.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,Gt,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(Gt,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),jt.meshes--}}function Wt(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{positions:[c,u,d,l,u,d,l,A,d,c,A,d,c,u,d,c,A,d,c,A,h,c,u,h,c,u,d,c,u,h,l,u,h,l,u,d,l,u,d,l,u,h,l,A,h,l,A,d,l,A,h,c,A,h,c,A,d,l,A,d,c,A,h,l,A,h,l,u,h,c,u,h],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Kt extends L{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const Xt={opaque:0,mask:1,blend:2},Yt=["opaque","mask","blend"];class Jt extends Kt{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new At({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Xt[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 Yt[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const Zt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class qt extends Kt{get type(){return"EmphasisMaterial"}get presets(){return Zt}constructor(e,t={}){super(e,t),this._state=new At({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(e=e||"default",this._preset===e)return;const t=Zt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Zt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const $t={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class ei extends Kt{get type(){return"EdgeMaterial"}get presets(){return $t}constructor(e,t={}){super(e,t),this._state=new At({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=$t[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys($t).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const ti={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class ii extends L{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ti}set units(e){e||(e="meters");ti[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class si extends L{constructor(e,t={}){super(e,t),this._supported=Te.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class ri extends L{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const oi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class ni extends Kt{get type(){return"PointsMaterial"}get presets(){return oi}constructor(e,t={}){super(e,t),this._state=new At({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=oi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(oi).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const ai={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class li extends Kt{get type(){return"LinesMaterial"}get presets(){return ai}constructor(e,t={}){super(e,t),this._state=new At({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ai[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ai).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function Ai(e,t){const i={};let s,r;for(let o=0,n=t.length;o{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new nt(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;ethis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+y.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],y.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get pickSurfacePrecisionEnabled(){return!1}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),!e&&!this._renderer.needsRender())return;t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;rr&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>n&&(n=e[5]),A=!0}A||(t=-100,i=-100,s=-100,r=100,o=100,n=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=n,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;if((e.snapToVertex||e.snapToEdge)&&!e.canvasPos)return void this.error("Scene.snapPick() `canvasPos` parameter expected for `snapToVertex:true` or `snapToEdge:true`");(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=Ai(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=Ai(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge);this.error("Scene.snapPick() canvasPos parameter expected")}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t{if(e.collidable){const l=e.aabb;l[0]o&&(o=l[3]),l[4]>n&&(n=l[4]),l[5]>a&&(a=l[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=n,e[5]=a,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){y.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:n,wrapperFunc:o},o}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const ci=1e3,ui=1001,di=1002,pi=1003,fi=1004,gi=1004,mi=1005,_i=1005,vi=1006,bi=1007,yi=1007,Bi=1008,wi=1008,xi=1009,Pi=1010,Ci=1011,Mi=1012,Ei=1013,Fi=1014,Ii=1015,Di=1016,Si=1017,Ti=1018,Li=1020,Ri=1021,Ui=1022,ki=1023,Oi=1024,Ni=1025,Qi=1026,Vi=1027,Hi=1028,ji=1029,Gi=1030,zi=1031,Wi=1033,Ki=33776,Xi=33777,Yi=33778,Ji=33779,Zi=35840,qi=35841,$i=35842,es=35843,ts=36196,is=37492,ss=37496,rs=37808,os=37809,ns=37810,as=37811,ls=37812,As=37813,hs=37814,cs=37815,us=37816,ds=37817,ps=37818,fs=37819,gs=37820,ms=37821,_s=36492,vs=3e3,bs=3001,ys=1e4,Bs=10001,ws=10002,xs=10003,Ps=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,n=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,A=[];A.push("#version 300 es"),A.push("// Lambertian drawing vertex shader"),A.push("in vec3 position;"),A.push("uniform mat4 modelMatrix;"),A.push("uniform mat4 viewMatrix;"),A.push("uniform mat4 projMatrix;"),A.push("uniform vec4 colorize;"),A.push("uniform vec3 offset;"),l&&A.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(A.push("uniform float logDepthBufFC;"),A.push("out float vFragDepth;"),A.push("bool isPerspectiveMatrix(mat4 m) {"),A.push(" return (m[2][3] == - 1.0);"),A.push("}"),A.push("out float isPerspective;"));a&&A.push("out vec4 vWorldPosition;");if(A.push("uniform vec4 lightAmbient;"),A.push("uniform vec4 materialColor;"),A.push("uniform vec3 materialEmissive;"),r.normalsBuf){A.push("in vec3 normal;"),A.push("uniform mat4 modelNormalMatrix;"),A.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),A.push(" }"),A.push(" return normalize(v);"),A.push("}"))}A.push("out vec4 vColor;"),"points"===r.primitiveName&&A.push("uniform float pointSize;");"spherical"!==o&&"cylindrical"!==o||(A.push("void billboard(inout mat4 mat) {"),A.push(" mat[0][0] = 1.0;"),A.push(" mat[0][1] = 0.0;"),A.push(" mat[0][2] = 0.0;"),"spherical"===o&&(A.push(" mat[1][0] = 0.0;"),A.push(" mat[1][1] = 1.0;"),A.push(" mat[1][2] = 0.0;")),A.push(" mat[2][0] = 0.0;"),A.push(" mat[2][1] = 0.0;"),A.push(" mat[2][2] =1.0;"),A.push("}"));A.push("void main(void) {"),A.push("vec4 localPosition = vec4(position, 1.0); "),A.push("vec4 worldPosition;"),l&&A.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?A.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):A.push("vec4 localNormal = vec4(normal, 0.0); "),A.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),A.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));A.push("mat4 viewMatrix2 = viewMatrix;"),A.push("mat4 modelMatrix2 = modelMatrix;"),n&&A.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(A.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),A.push("billboard(modelMatrix2);"),A.push("billboard(viewMatrix2);"),A.push("billboard(modelViewMatrix);"),r.normalsBuf&&(A.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),A.push("billboard(modelNormalMatrix2);"),A.push("billboard(viewNormalMatrix2);"),A.push("billboard(modelViewNormalMatrix);")),A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(A.push("worldPosition = modelMatrix2 * localPosition;"),A.push("worldPosition.xyz = worldPosition.xyz + offset;"),A.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&A.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(A.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),A.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),A.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e0,o=t.gammaOutput,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}"points"===s.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");o?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(e)):(this.vertex=function(e){const t=e.scene;e._material;const i=e._state,s=t._sectionPlanesState,r=e._geometry._state,o=t._lightsState;let n;const a=i.billboard,l=i.background,A=i.stationary,h=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=Es(e),u=s.getNumAllocatedSectionPlanes()>0,d=Ms(e),p=!!r.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),u&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(let e=0,t=o.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}h&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));r.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===r.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=o.lights.length;e0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=o.lights.length;e0,l=Es(e),A=s.uvBuf,h="PhongMaterial"===n.type,c="MetallicMaterial"===n.type,u="SpecularMaterial"===n.type,d=Ms(e);t.gammaInput;const p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),h&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = "+Cs[o.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||u)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+Cs[o.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(o.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));n.ambient&&f.push("uniform vec3 materialAmbient;");n.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==n.alpha&&null!==n.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");n.emissive&&f.push("uniform vec3 materialEmissive;");n.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==n.glossiness&&null!==n.glossiness&&f.push("uniform float materialGlossiness;");void 0!==n.shininess&&null!==n.shininess&&f.push("uniform float materialShininess;");n.specular&&f.push("uniform vec3 materialSpecular;");void 0!==n.metallic&&null!==n.metallic&&f.push("uniform float materialMetallic;");void 0!==n.roughness&&null!==n.roughness&&f.push("uniform float materialRoughness;");void 0!==n.specularF0&&null!==n.specularF0&&f.push("uniform float materialSpecularF0;");A&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));A&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));A&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));A&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&A&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&A&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&A&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));A&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));A&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&A&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&A&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&A&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(let e=0,t=o.lights.length;e 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),n.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");n.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):n.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");n.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");n.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==n.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==n.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==n.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==n.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==n.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");A&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));A&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+Cs[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));A&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+Cs[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));A&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+Cs[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));A&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+Cs[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));A&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));A&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){A&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),A&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),A&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),A&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),A&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),A&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),A&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),h&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),u&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),h&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(u||c)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(h=0,c=o.sectionPlanes.length;h0&&r.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Ts{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,o=!!e._geometry._state.compressGeometry,n=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===n||"cylindrical"===n)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===n&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e0,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ls=new e({}),Rs=d.vec3(),Us=function(e,t){this.id=Ls.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ts(t),this._allocate(t)},ks={};Us.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=ks[t];return i||(i=new Us(t,e),ks[t]=i,m.memory.programs++),i._useCount++,i},Us.prototype.put=function(){0==--this._useCount&&(Ls.removeItem(this.id),this._program&&this._program.destroy(),delete ks[this._hash],m.memory.programs--)},Us.prototype.webglContextRestored=function(){this._program=null},Us.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,n=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,A=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,A?e.getRTCViewMatrix(a.originHash,A):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Edges drawing vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec4 edgeColor;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));i&&n.push("out vec4 vWorldPosition;");n.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));n.push("vColor = edgeColor;"),i&&n.push("vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,o=[];o.push("#version 300 es"),o.push("// Edges drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),o.push("}")}t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)}}const Ns=new e({}),Qs=d.vec3(),Vs=function(e,t){this.id=Ns.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Os(t),this._allocate(t)},Hs={};Vs.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Hs[t];return i||(i=new Vs(t,e),Hs[t]=i,m.memory.programs++),i._useCount++,i},Vs.prototype.put=function(){0==--this._useCount&&(Ns.removeItem(this.id),this._program&&this._program.destroy(),delete Hs[this._hash],m.memory.programs--)},Vs.prototype.webglContextRestored=function(){this._program=null},Vs.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let n;const a=t._state,l=t._geometry,A=l._state,h=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(a.originHash,h):r.viewMatrix),a.clippable){const e=s._sectionPlanesState.getNumAllocatedSectionPlanes(),i=s._sectionPlanesState.sectionPlanes.length;if(e>0){const r=s._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh picking vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("out vec4 vViewPosition;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("uniform vec2 pickClipPos;"),n.push("vec4 remapClipPos(vec4 clipPos) {"),n.push(" clipPos.xy /= clipPos.w;"),n.push(" clipPos.xy -= pickClipPos;"),n.push(" clipPos.xy *= clipPos.w;"),n.push(" return clipPos;"),n.push("}"),n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"));n.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = remapClipPos(clipPos);"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(e)}}const Gs=d.vec3(),zs=function(e,t){this._hash=e,this._shaderSource=new js(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ws={};zs.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Ws[t];if(!i){if(i=new zs(t,e),i.errors)return console.log(i.errors.join("\n")),null;Ws[t]=i,m.memory.programs++}return i._useCount++,i},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ws[this._hash],m.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t>24&255,h=l>>16&255,c=l>>8&255,u=255&l;s.uniform4f(this._uPickColor,u/255,c/255,h/255,A/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),n.indicesBuf?(s.drawElements(n.primitive,n.indicesBuf.numItems,n.indicesBuf.itemType,0),e.drawElements++):n.positions&&s.drawArrays(s.TRIANGLES,0,n.positions.numItems)},zs.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new He(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(let e=0;e 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(e)}}const Xs=d.vec3(),Ys=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ks(t),this._allocate(t)},Js={};Ys.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Js[t];if(!i){if(i=new Ys(t,e),i.errors)return console.log(i.errors.join("\n")),null;Js[t]=i,m.memory.programs++}return i._useCount++,i},Ys.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Js[this._hash],m.memory.programs--)},Ys.prototype.webglContextRestored=function(){this._program=null},Ys.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,n=t._geometry,a=t._geometry._state,l=t.origin,A=o.backfaces,h=o.frontface,c=i.camera.project,u=n._getPickTrianglePositions(),d=n._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,n=[];n.push("#version 300 es"),n.push("// Mesh occlusion vertex shader"),n.push("in vec3 position;"),n.push("uniform mat4 modelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform vec3 offset;"),s&&n.push("uniform mat4 positionsDecodeMatrix;");i&&n.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(n.push("void billboard(inout mat4 mat) {"),n.push(" mat[0][0] = 1.0;"),n.push(" mat[0][1] = 0.0;"),n.push(" mat[0][2] = 0.0;"),"spherical"===r&&(n.push(" mat[1][0] = 0.0;"),n.push(" mat[1][1] = 1.0;"),n.push(" mat[1][2] = 0.0;")),n.push(" mat[2][0] = 0.0;"),n.push(" mat[2][1] = 0.0;"),n.push(" mat[2][2] =1.0;"),n.push("}"));n.push("void main(void) {"),n.push("vec4 localPosition = vec4(position, 1.0); "),n.push("vec4 worldPosition;"),s&&n.push("localPosition = positionsDecodeMatrix * localPosition;");n.push("mat4 viewMatrix2 = viewMatrix;"),n.push("mat4 modelMatrix2 = modelMatrix;"),o&&n.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(n.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),n.push("billboard(modelMatrix2);"),n.push("billboard(viewMatrix2);"),n.push("billboard(modelViewMatrix);"),n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(n.push("worldPosition = modelMatrix2 * localPosition;"),n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&n.push(" vWorldPosition = worldPosition;");n.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return n.push("gl_Position = clipPos;"),n.push("}"),n}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(e)}}const qs=d.vec3(),$s=function(e,t){this._hash=e,this._shaderSource=new Zs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},er={};$s.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";");let i=er[t];if(!i){if(i=new $s(t,e),i.errors)return console.log(i.errors.join("\n")),null;er[t]=i,m.memory.programs++}return i._useCount++,i},$s.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete er[this._hash],m.memory.programs--)},$s.prototype.webglContextRestored=function(){this._program=null},$s.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,n=t._geometry._state,a=t.origin;if(r.alpha<1)return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(o.originHash,a):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.getNumAllocatedSectionPlanes(),r=i._sectionPlanesState.sectionPlanes.length;if(e>0){const o=i._sectionPlanesState.sectionPlanes,n=t.renderFlags;for(let t=0;t0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var o=0;o 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const ir=function(e,t){this._hash=e,this._shaderSource=new tr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},sr={};ir.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=sr[i];if(!s){if(s=new ir(i,e),s.errors)return console.log(s.errors.join("\n")),null;sr[i]=s,m.memory.programs++}return s._useCount++,s},ir.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete sr[this._hash],m.memory.programs--)},ir.prototype.webglContextRestored=function(){this._program=null},ir.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},ir.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new He(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e0){let e,t,r,o,n;for(let a=0,l=this._uSectionPlanes.length;a0)for(let i=0;i0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const gr=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),o=d.vec3(),n=d.vec4(),a=d.vec3(),l=d.vec3(),A=d.vec3(),h=d.vec3(),c=d.vec3(),u=d.vec3(),p=d.vec3(),f=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),v=d.vec4(),b=d.vec3(),y=d.vec3(),B=d.vec3(),w=d.vec3(),x=d.vec3(),P=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),I=d.vec3();return function(D,S,T,L){var R=L.primIndex;if(null!=R&&R>-1){const N=D.geometry._state,Q=D.scene,V=Q.camera,H=Q.canvas;if("triangles"===N.primitiveName){L.primitive="triangle";const Q=R,j=N.indices,G=N.positions;let z,W,X;if(j){var U=j[Q+0],k=j[Q+1],O=j[Q+2];o[0]=U,o[1]=k,o[2]=O,L.indices=o,z=3*U,W=3*k,X=3*O}else z=3*Q,W=z+3,X=W+3;if(i[0]=G[z+0],i[1]=G[z+1],i[2]=G[z+2],s[0]=G[W+0],s[1]=G[W+1],s[2]=G[W+2],r[0]=G[X+0],r[1]=G[X+1],r[2]=G[X+2],N.compressGeometry){const e=N.positionsDecodeMatrix;e&&(Ht.decompressPosition(i,e,i),Ht.decompressPosition(s,e,s),Ht.decompressPosition(r,e,r))}L.canvasPos?d.canvasPosToLocalRay(H.canvas,D.origin?K(S,D.origin):S,T,D.worldMatrix,L.canvasPos,e,t):L.origin&&L.direction&&d.worldRayToLocalRay(D.worldMatrix,L.origin,L.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,n),L.localPos=n,L.position=n,m[0]=n[0],m[1]=n[1],m[2]=n[2],m[3]=1,d.transformVec4(D.worldMatrix,m,_),a[0]=_[0],a[1]=_[1],a[2]=_[2],L.canvasPos&&D.origin&&(a[0]+=D.origin[0],a[1]+=D.origin[1],a[2]+=D.origin[2]),L.worldPos=a,d.transformVec4(V.matrix,_,v),l[0]=v[0],l[1]=v[1],l[2]=v[2],L.viewPos=l,d.cartesianToBarycentric(n,i,s,r,A),L.bary=A;const Y=N.normals;if(Y){if(N.compressGeometry){const e=3*U,t=3*k,i=3*O;Ht.decompressNormal(Y.subarray(e,e+2),h),Ht.decompressNormal(Y.subarray(t,t+2),c),Ht.decompressNormal(Y.subarray(i,i+2),u)}else h[0]=Y[z],h[1]=Y[z+1],h[2]=Y[z+2],c[0]=Y[W],c[1]=Y[W+1],c[2]=Y[W+2],u[0]=Y[X],u[1]=Y[X+1],u[2]=Y[X+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(h,A[0],b),d.mulVec3Scalar(c,A[1],y),B),d.mulVec3Scalar(u,A[2],w),x);L.worldNormal=d.normalizeVec3(d.transformVec3(D.worldNormalMatrix,e,P))}const J=N.uv;if(J){if(p[0]=J[2*U],p[1]=J[2*U+1],f[0]=J[2*k],f[1]=J[2*k+1],g[0]=J[2*O],g[1]=J[2*O+1],N.compressGeometry){const e=N.uvDecodeMatrix;e&&(Ht.decompressUV(p,e,p),Ht.decompressUV(f,e,f),Ht.decompressUV(g,e,g))}L.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(p,A[0],C),d.mulVec2Scalar(f,A[1],M),E),d.mulVec2Scalar(g,A[2],F),I)}}}}}();function mr(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const n=!!e.openEnded;let a=e.center;const l=a?a[0]:0,A=a?a[1]:0,h=a?a[2]:0,c=s/2,u=s/o,d=2*Math.PI/r,p=1/r,f=(t-i)/o,g=[],m=[],_=[],v=[];let b,B,w,x,P,C,M,E,F,I,D;const S=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(b=0;b<=o;b++)for(P=t-b*f,C=c-b*u,B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),m.push(P*w),m.push(S),m.push(P*x),_.push(B*p),_.push(1*b/o),g.push(P*w+l),g.push(C+A),g.push(P*x+h);for(b=0;b0){for(F=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(c+A),g.push(0+h),B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(t*w),m.push(1),m.push(t*x),_.push(I),_.push(D),g.push(t*w+l),g.push(c+A),g.push(t*x+h);for(B=0;B0){for(F=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+l),g.push(0-c+A),g.push(0+h),B=0;B<=r;B++)w=Math.sin(B*d),x=Math.cos(B*d),I=.5*Math.sin(B*d)+.5,D=.5*Math.cos(B*d)+.5,m.push(i*w),m.push(-1),m.push(i*x),_.push(I),_.push(D),g.push(i*w+l),g.push(0-c+A),g.push(i*x+h);for(B=0;B":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function br(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],o=e.size||1,n=[],a=[],l=e.text;y.isNumeric(l)&&(l=""+l);for(var A,h,c,u,d,p,f,g,m,_=(l||"").split("\n"),v=0,b=0,B=.04,w=0;w<_.length;w++){A=0,c=(h=_[w]).length;for(var x=0;x0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const o=Qr(i,this.wrapS);o&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,o);const n=Qr(i,this.wrapT);if(n&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,n),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=Qr(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Gr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Gr(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Qr(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Qr(i,this.magFilter)));const a=Qr(i,this.format,this.encoding),l=Qr(i,this.type),A=jr(i,this.internalFormat,a,l,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,A,e[0].width,e[0].height);for(let t=0,s=e.length;t>t;return e+1}class Xr extends L{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new At({texture:new Hr({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this._state.texture=new Hr({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=zr(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=zr(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}class Yr extends L{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new At({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}const Jr=m.memory,Zr=d.AABB3();class qr extends Lt{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new At({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=Ht.getPositionsBounds(t.positions),o=Ht.compressPositions(t.positions,e.min,e.max);r=o.quantized,i.positionsDecodeMatrix=o.decodeMatrix,i.positionsBuf=new je(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),Jr.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,Zr,i.positionsDecodeMatrix),d.AABB3ToOBB3(Zr,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new je(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),Jr.colors+=i.colorsBuf.numItems}if(t.uv){const e=Ht.getUVBounds(t.uv),r=Ht.compressUVs(t.uv,e.min,e.max),o=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new je(s,s.ARRAY_BUFFER,o,o.length,2,s.STATIC_DRAW),Jr.uvs+=i.uvBuf.numItems}if(t.normals){const e=Ht.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new je(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),Jr.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),Jr.indices+=i.indicesBuf.numItems;const o=Rt(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,o,o.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),Jr.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(),Jr.meshes--}}var $r={};function eo(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var o=$r.parse.from3DS(e).edit.objects[0].mesh,n=o.vertices,a=o.uvt,l=o.indices;r.processes--,i(y.apply(t,{primitive:"triangles",positions:n,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function to(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,y.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var o=$r.parse.fromOBJ(e),n=$r.edit.unwrap(o.i_verts,o.c_verts,3),a=$r.edit.unwrap(o.i_norms,o.c_norms,3),l=$r.edit.unwrap(o.i_uvt,o.c_uvt,2),A=new Int32Array(o.i_verts.length),h=0;h0?a:null,autoNormals:0===a.length,uv:l,indices:A}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function io(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,n=r?r[1]:0,a=r?r[2]:0,l=-t+o,A=-i+n,h=-s+a,c=t+o,u=i+n,d=s+a;return y.apply(e,{primitive:"lines",positions:[l,A,h,l,A,d,l,u,h,l,u,d,c,A,h,c,A,d,c,u,h,c,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function so(e={}){return io({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function ro(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,o=[],n=[];let a=0;for(let e=0,t=-r;e<=i;e++,t+=s)o.push(-r),o.push(0),o.push(t),o.push(r),o.push(0),o.push(t),o.push(t),o.push(0),o.push(-r),o.push(t),o.push(0),o.push(r),n.push(a++),n.push(a++),n.push(a++),n.push(a++);return y.apply(e,{primitive:"lines",positions:o,indices:n})}function oo(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const o=e.center,n=o?o[0]:0,a=o?o[1]:0,l=o?o[2]:0,A=t/2,h=i/2,c=Math.floor(s)||1,u=Math.floor(r)||1,d=c+1,p=u+1,f=t/c,g=i/u,m=new Float32Array(d*p*3),_=new Float32Array(d*p*3),v=new Float32Array(d*p*2);let b,B,w,x,P,C,M,E=0,F=0;for(b=0;b65535?Uint32Array:Uint16Array)(c*u*6);for(b=0;b360&&(o=360);const n=e.center;let a=n?n[0]:0,l=n?n[1]:0;const A=n?n[2]:0,h=[],c=[],u=[],p=[];let f,g,m,_,v,b,B,w,x,P,C,M;for(w=0;w<=r;w++)for(B=0;B<=s;B++)f=B/s*o,g=.785398+w/r*Math.PI*2,a=t*Math.cos(f),l=t*Math.sin(f),m=(t+i*Math.cos(g))*Math.cos(f),_=(t+i*Math.cos(g))*Math.sin(f),v=i*Math.sin(g),h.push(m+a),h.push(_+l),h.push(v+A),u.push(1-B/s),u.push(w/r),b=d.normalizeVec3(d.subVec3([m,_,v],[a,l,A],[]),[]),c.push(b[0]),c.push(b[1]),c.push(b[2]);for(w=1;w<=r;w++)for(B=1;B<=s;B++)x=(s+1)*w+B-1,P=(s+1)*(w-1)+B-1,C=(s+1)*(w-1)+B,M=(s+1)*w+B,p.push(x),p.push(P),p.push(C),p.push(C),p.push(M),p.push(x);return y.apply(e,{positions:h,normals:c,uv:u,indices:p})}function ao(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e[...e])).flat();return ao({id:e.id,points:t})}$r.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},$r.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa($r.parse._buffToStr(e));window.location.href=i},$r.clone=function(e){return JSON.parse(JSON.stringify(e))},$r.bin={},$r.bin.f=new Float32Array(1),$r.bin.fb=new Uint8Array($r.bin.f.buffer),$r.bin.rf=function(e,t){for(var i=$r.bin.f,s=$r.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},$r.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},$r.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},$r.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},$r.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},$r.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},$r.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},$r.parse={},$r.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),Ao&&(o=A),hn&&(n=h)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:n}}};class Ao extends L{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new Xr(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Sr(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new fr(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new zt(this,oo({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const ho=d.OBB3(),co=d.OBB3(),uo=d.OBB3();class po{constructor(e,t,i,s,r,o,n=null,a=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=n,this.portionId=a,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this)}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex(this.portionId,e)}set aabb(e){this._aabbLocal=e}get aabb(){if(this._aabbWorldDirty){if(d.AABB3ToOBB3(this._aabbLocal,ho),this.transform?(d.transformOBB3(this.transform.worldMatrix,ho,co),d.transformOBB3(this.model.worldMatrix,co,uo),d.OBB3ToAABB3(uo,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,ho,co),d.OBB3ToAABB3(co,this._aabbWorld)),this.origin){const e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const fo=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 go=0;const mo={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},_o=new Float32Array([1,1,1,1]),vo=new Float32Array([0,0,0,1]),bo=d.vec4(),yo=d.vec3(),Bo=d.vec3(),wo=d.mat4();class xo{constructor(e,t=!1,{instancing:i=!1,edges:s=!1}={}){this._scene=e,this._withSAO=t,this._instancing=i,this._edges=s,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}_getHash(){return this._scene._sectionPlanesState.getHash()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){return[""]}_buildFragmentShader(){return[""]}_addMatricesUniformBlockLines(e,t=!1){return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}_addRemapClipPosLines(e,t=1){return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(` clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(${t}));`),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}getValid(){return this._hash===this._getHash()}setSectionPlanesStateUniforms(e){const t=this._scene,{gl:i}=t.canvas,{model:s,layerIndex:r}=e,o=t._sectionPlanesState.getNumAllocatedSectionPlanes(),n=t._sectionPlanesState.sectionPlanes.length;if(o>0){const a=t._sectionPlanesState.sectionPlanes,l=r*n,A=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(let t=0;t0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0&&p.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,p.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),p.lightMaps.length>0&&p.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,p.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++),this._withSAO){const t=n.sao;if(t.possible){const i=a.drawingBufferWidth,s=a.drawingBufferHeight;bo[0]=i,bo[1]=s,bo[2]=t.blendCutoff,bo[3]=t.blendFactor,a.uniform4fv(this._uSAOParams,bo),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%o,e.bindTexture++}}if(s){const e=this._edges?"edgeColor":"fillColor",t=this._edges?"edgeAlpha":"fillAlpha";if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_XRAYED"]){const i=n.xrayMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_HIGHLIGHTED"]){const i=n.highlightMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else if(i===mo[(this._edges?"EDGES":"SILHOUETTE")+"_SELECTED"]){const i=n.selectedMaterial._state,s=i[e],r=i[t];a.uniform4f(this._uColor,s[0],s[1],s[2],r)}else a.uniform4fv(this._uColor,this._edges?vo:_o)}this._draw({state:l,frameCtx:e,incrementDrawState:r}),a.bindVertexArray(null)}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,m.memory.programs--}}class Po extends xo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!1,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{const e=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,e,i.indicesBuf.itemType,o),r&&s.drawElements++}}}class Co extends Po{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r;const o=[];o.push("#version 300 es"),o.push("// Triangles batching draw vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;")),o.push("out vec4 vColor;"),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Mo extends Po{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,i=t.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching silhouette fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r){for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = newColor;"),o.push("}"),o}}class Fo extends Po{constructor(e){super(e,!1,{instancing:!1,edges:!0})}}class Io extends Fo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Do extends Fo{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class So extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class To extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Lo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Ro extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Uo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}class ko extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class Oo extends Po{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}class No extends Po{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Triangles batching quality draw vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),o.push("vFragDepth = 1.0 + clipPos.w;")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Triangles batching quality draw fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),n.push("uniform sampler2D uAOMap;"),n.push("in vec4 vViewPosition;"),n.push("in vec3 vViewNormal;"),n.push("in vec4 vColor;"),n.push("in vec2 vUV;"),n.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Vo extends Po{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Triangles batching color texture fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),o.push("uniform float gammaFactor;"),o.push("vec4 linearToLinear( in vec4 value ) {"),o.push(" return value;"),o.push("}"),o.push("vec4 sRGBToLinear( in vec4 value ) {"),o.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),o.push("}"),o.push("vec4 gammaToLinear( in vec4 value) {"),o.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),o.push("}"),t&&(o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(let e=0,t=s.getNumAllocatedSectionPlanes();e sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(let e=0,t=i.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Xo=d.vec3(),Yo=d.vec3(),Jo=d.vec3(),Zo=d.vec3(),qo=d.mat4();class $o extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Xo;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Yo;if(l){const e=Jo;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,qo),m=Zo,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElements(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class en{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new Eo(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new So(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new To(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new $o(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Co(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Co(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Mo(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Mo(this._scene,!0)),this._flatColorRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Vo(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Vo(this._scene,!0)),this._colorTextureRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new No(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new No(this._scene,!0)),this._pbrRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Eo(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Uo(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new ko(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Io(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Do(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new So(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Lo(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Qo(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new To(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ro(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Oo(this._scene)),this._shadowRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new $o(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ko(this._scene)),this._snapInitRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const tn={};let sn=65536,rn=5e6;class on{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),sn=e}get maxDataTextureHeight(){return sn}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),rn=e}get maxGeometryBatchSize(){return rn}}const nn=new on;class an{constructor(){this.maxVerts=nn.maxGeometryBatchSize,this.maxIndices=3*nn.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const ln=d.mat4(),An=d.mat4();function hn(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],n=t[1],a=t[2],l=t[3]-o,A=t[4]-n,h=t[5]-a,c=65525,u=c/l,p=c/A,f=c/h,g=e=>e>=0?e:0;for(let t=0;t=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function dn(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const pn=d.mat4(),fn=d.mat4(),gn=d.vec4([0,0,0,1]),mn=d.vec3(),_n=d.vec3(),vn=d.vec3(),bn=d.vec3(),yn=d.vec3(),Bn=d.vec3(),wn=d.vec3();class xn{constructor(e){console.info("Creating VBOBatchingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesBatchingLayer"+(e.solid?"-solid":"-surface")+(e.autoNormals?"-autonormals":"-normals")+(e.textureSet&&e.textureSet.colorTexture?"-colorTexture":"")+(e.textureSet&&e.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=tn[t];return i||(i=new en(e),tn[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete tn[t],i._destroy()}))),i}(e.model.scene),this._buffer=new an(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({origin:d.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:e.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=d.mat4(e.positionsDecodeMatrix)),e.uvDecodeMatrix?(this._state.uvDecodeMatrix=d.mat3(e.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,e.origin&&this._state.origin.set(e.origin),this.solid=!!e.solid}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)for(let e=0,t=o.length;e0){const e=pn;m?d.inverseMat4(d.transposeMat4(m,fn),e):d.identityMat4(e,e),function(e,t,i,s,r){function o(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let n,a,l,A,h,c,u=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;ch&&(l=n,h=A),n=un(p,"floor","ceil"),a=dn(n),A=o(p,a),A>h&&(l=n,h=A),n=un(p,"ceil","ceil"),a=dn(n),A=o(p,a),A>h&&(l=n,h=A),s[r+c+0]=l[0],s[r+c+1]=l[1],s[r+c+2]=0}(e,r,r.length,b.normals,b.normals.length)}if(l)for(let e=0,t=l.length;e0)for(let e=0,t=n.length;e0)for(let e=0,t=a.length;e0){const s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):hn(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=d.mat4());if(e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(let e=0,t=this._portions.length;e0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new je(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.uv.length>0)if(e.uvDecodeMatrix){let s=!1;e.uvBuf=new je(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,s)}else{const s=Ht.getUVBounds(i.uv),r=Ht.compressUVs(i.uv,s.min,s.max),o=r.quantized;let n=!1;e.uvDecodeMatrix=d.mat3(r.decodeMatrix),e.uvBuf=new je(t,t.ARRAY_BUFFER,o,o.length,2,t.STATIC_DRAW,n)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new je(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s),o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new je(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const s=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}isEmpty(){return!this._state.indicesBuf}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=e,s=this._portions[i],r=4*s.vertsBaseIndex,o=4*s.numVerts,n=this._scratchMemory.getUInt8Array(o),a=t[0],l=t[1],A=t[2],h=t[3];for(let e=0;e_)&&(_=e,s.set(v),r&&d.triangleNormal(p,f,g,r),m=!0)}}return m&&r&&(d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),m}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}class Pn extends xo{constructor(e,t,{edges:i=!1}={}){super(e,t,{instancing:!0,edges:i})}_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}class Cn extends Pn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0;let r,o,n;const a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),e.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),e.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),s&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}class Mn extends Pn{_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState;let s,r;const o=t.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry flat-shading drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),o){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}for(n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),s=0,r=i.lights.length;s0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}class Fn extends Pn{constructor(e,t){super(e,t,{instancing:!0,edges:!0})}}class In extends Fn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Dn extends Fn{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!1})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Sn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Tn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class Ln extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(` outNormal = ivec4(vWorldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Rn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}class Un extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry depth drawing fragment shader"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),o.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),o.push("}"),o}}class kn extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}class On extends Pn{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Nn={3e3:"linearToLinear",3001:"sRGBToLinear"};class Qn extends Pn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,o=[];return o.push("#version 300 es"),o.push("// Instancing geometry quality drawing vertex shader"),o.push("uniform int renderPass;"),o.push("in vec3 position;"),o.push("in vec3 normal;"),o.push("in vec4 color;"),o.push("in vec2 uv;"),o.push("in vec2 metallicRoughness;"),o.push("in float flags;"),e.entityOffsetsEnabled&&o.push("in vec3 offset;"),o.push("in vec4 modelMatrixCol0;"),o.push("in vec4 modelMatrixCol1;"),o.push("in vec4 modelMatrixCol2;"),o.push("in vec4 modelNormalMatrixCol0;"),o.push("in vec4 modelNormalMatrixCol1;"),o.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(o,!0),o.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;")),o.push("vec3 octDecode(vec2 oct) {"),o.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push(" if (v.z < 0.0) {"),o.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push(" }"),o.push(" return normalize(v);"),o.push("}"),o.push("out vec4 vViewPosition;"),o.push("out vec3 vViewNormal;"),o.push("out vec4 vColor;"),o.push("out vec2 vUV;"),o.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("out vec3 vWorldNormal;"),s&&(o.push("out vec4 vWorldPosition;"),o.push("out float vFlags;"),r&&o.push("out vec4 vClipPosition;")),o.push("void main(void) {"),o.push("int colorFlag = int(flags) & 0xF;"),o.push("if (colorFlag != renderPass) {"),o.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags = flags;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,o=i.clippingCaps,n=[];n.push("#version 300 es"),n.push("// Instancing geometry quality drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),n.push("uniform sampler2D uMetallicRoughMap;"),n.push("uniform sampler2D uEmissiveMap;"),n.push("uniform sampler2D uNormalMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),s.reflectionMaps.length>0&&n.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&n.push("uniform samplerCube lightMap;"),n.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e0&&n.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(n,!0),n.push("#define PI 3.14159265359"),n.push("#define RECIPROCAL_PI 0.31830988618"),n.push("#define RECIPROCAL_PI2 0.15915494"),n.push("#define EPSILON 1e-6"),n.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),n.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),n.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),n.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),n.push(" return normalize(surf_norm );"),n.push(" }"),n.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),n.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),n.push(" vec2 st0 = dFdx( uv.st );"),n.push(" vec2 st1 = dFdy( uv.st );"),n.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),n.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),n.push(" vec3 N = normalize( surf_norm );"),n.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),n.push(" mat3 tsn = mat3( S, T, N );"),n.push(" return normalize( tsn * mapN );"),n.push("}"),n.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),n.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),n.push("}"),n.push("struct IncidentLight {"),n.push(" vec3 color;"),n.push(" vec3 direction;"),n.push("};"),n.push("struct ReflectedLight {"),n.push(" vec3 diffuse;"),n.push(" vec3 specular;"),n.push("};"),n.push("struct Geometry {"),n.push(" vec3 position;"),n.push(" vec3 viewNormal;"),n.push(" vec3 worldNormal;"),n.push(" vec3 viewEyeDir;"),n.push("};"),n.push("struct Material {"),n.push(" vec3 diffuseColor;"),n.push(" float specularRoughness;"),n.push(" vec3 specularColor;"),n.push(" float shine;"),n.push("};"),n.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),n.push(" float r = ggxRoughness + 0.0001;"),n.push(" return (2.0 / (r * r) - 2.0);"),n.push("}"),n.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),n.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),n.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),n.push("}"),s.reflectionMaps.length>0&&(n.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),n.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),n.push(" vec3 envMapColor = "+Nn[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),n.push(" return envMapColor;"),n.push("}")),n.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),n.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),n.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),n.push("}"),n.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" return 1.0 / ( gl * gv );"),n.push("}"),n.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),n.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),n.push(" return 0.5 / max( gv + gl, EPSILON );"),n.push("}"),n.push("float D_GGX(const in float alpha, const in float dotNH) {"),n.push(" float a2 = ( alpha * alpha );"),n.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),n.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float alpha = ( roughness * roughness );"),n.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),n.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),n.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),n.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),n.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),n.push(" vec3 F = F_Schlick( specularColor, dotLH );"),n.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),n.push(" float D = D_GGX( alpha, dotNH );"),n.push(" return F * (G * D);"),n.push("}"),n.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),n.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),n.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),n.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),n.push(" vec4 r = roughness * c0 + c1;"),n.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),n.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),n.push(" return specularColor * AB.x + AB.y;"),n.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(n.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(n.push(" vec3 irradiance = "+Nn[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),n.push(" irradiance *= PI;"),n.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(n.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),n.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),n.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),n.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),n.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),n.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),n.push("}")),n.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),n.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),n.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),n.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),n.push("}"),n.push("out vec4 outColor;"),n.push("void main(void) {"),r){n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e (0.002 * vClipPosition.w)) {"),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push(" return;"),n.push("}")):(n.push(" if (dist > 0.0) { "),n.push(" discard;"),n.push(" }")),n.push("}")}n.push("IncidentLight light;"),n.push("Material material;"),n.push("Geometry geometry;"),n.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),n.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),n.push("float opacity = float(vColor.a) / 255.0;"),n.push("vec3 baseColor = rgb;"),n.push("float specularF0 = 1.0;"),n.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),n.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),n.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),n.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),n.push("baseColor *= colorTexel.rgb;"),n.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),n.push("metallic *= metalRoughTexel.b;"),n.push("roughness *= metalRoughTexel.g;"),n.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),n.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),n.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),n.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),n.push("geometry.position = vViewPosition.xyz;"),n.push("geometry.viewNormal = -normalize(viewNormal);"),n.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&n.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&n.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(let e=0;e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),s.push("}"),s}}class Hn extends Pn{_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState;let r,o;const n=i.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),n){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(let e=0,t=i.getNumAllocatedSectionPlanes();e sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),r=0,o=s.lights.length;r0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yn=d.vec3(),Jn=d.vec3(),Zn=d.vec3(),qn=d.vec3(),$n=d.mat4();class ea extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Yn;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Jn;if(l){const e=d.transformPoint3(h,l,Zn);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,$n),m=qn,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ta{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Sn(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Tn(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Xn(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new ea(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Cn(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Cn(this._scene,!0)),this._colorRendererWithSAO}get flatColorRenderer(){return this._flatColorRenderer||(this._flatColorRenderer=new Mn(this._scene,!1)),this._flatColorRenderer}get flatColorRendererWithSAO(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new Mn(this._scene,!0)),this._flatColorRendererWithSAO}get pbrRenderer(){return this._pbrRenderer||(this._pbrRenderer=new Qn(this._scene,!1)),this._pbrRenderer}get pbrRendererWithSAO(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new Qn(this._scene,!0)),this._pbrRendererWithSAO}get colorTextureRenderer(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Hn(this._scene,!1)),this._colorTextureRenderer}get colorTextureRendererWithSAO(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Hn(this._scene,!0)),this._colorTextureRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new En(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Un(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new kn(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new In(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Dn(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Sn(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ln(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Vn(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Tn(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Rn(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new On(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Xn(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new ea(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const ia={};const sa=new Uint8Array(4),ra=new Float32Array(1),oa=d.vec4([0,0,0,1]),na=new Float32Array(3),aa=d.vec3(),la=d.vec3(),Aa=d.vec3(),ha=d.vec3(),ca=d.vec3(),ua=d.vec3(),da=d.vec3(),pa=new Float32Array(4);class fa{constructor(e){console.info("Creating VBOInstancingTrianglesLayer"),this.model=e.model,this.sortId="TrianglesInstancingLayer"+(e.solid?"-solid":"-surface")+(e.normals?"-normals":"-autoNormals"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=ia[t];return i||(i=new ta(e),ia[t]=i,i._compile(),i.eagerCreateRenders(),e.on("compile",(()=>{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete ia[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({numInstances:0,obb:d.OBB3(),origin:d.vec3(),geometry:e.geometry,textureSet:e.textureSet,pbrSupported:!1,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&this._state.origin.set(e.origin),this._finalized=!1,this.solid=!!e.solid,this.numIndices=e.geometry.numIndices}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;e.colorsBuf=new je(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;e.metallicRoughnessBuf=new je(s,s.ARRAY_BUFFER,t,this._metallicRoughness.length,2,s.STATIC_DRAW,i)}if(o>0){let t=!1;e.flagsBuf=new je(s,s.ARRAY_BUFFER,new Float32Array(o),o,1,s.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;e.offsetsBuf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,t),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){const i=!1;e.positionsBuf=new je(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,i),e.positionsDecodeMatrix=d.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){const i=new Uint8Array(t.colorsCompressed),r=!1;e.colorsBuf=new je(s,s.ARRAY_BUFFER,i,i.length,4,s.STATIC_DRAW,r)}if(t.uvCompressed&&t.uvCompressed.length>0){const i=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new je(s,s.ARRAY_BUFFER,i,i.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new je(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){const t=!1;e.modelMatrixCol0Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelMatrixCol1Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelMatrixCol2Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol1Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,t),e.modelNormalMatrixCol2Buf=new je(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){const t=!1;e.pickColorsBuf=new je(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,t),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";sa[0]=t[0],sa[1]=t[1],sa[2]=t[2],sa[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(sa,4*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?1:0)<<16,ra[0]=d,this._state.flagsBuf&&this._state.flagsBuf.setData(ra,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(na[0]=t[0],na[1]=t[1],na[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(na,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}getEachVertex(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;const i=this._state,s=i.geometry,r=this._portions[e];if(!r)return void this.model.error("portion not found: "+e);const o=s.quantizedPositions,n=i.origin,a=r.offset,l=n[0]+a[0],A=n[1]+a[1],h=n[2]+a[2],c=oa,u=r.matrix,p=this.model.sceneModelMatrix,f=i.positionsDecodeMatrix;for(let e=0,i=o.length;ev)&&(v=e,s.set(b),r&&d.triangleNormal(f,g,m,r),_=!0)}}return _&&r&&(d.transformVec3(a.normalMatrix,r,r),d.transformVec3(this.model.worldNormalMatrix,r,r),d.normalizeVec3(r)),_}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}class ga extends xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}class ma extends ga{drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class _a extends ga{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const va=d.vec3(),ba=d.vec3(),ya=d.vec3(),Ba=d.vec3(),wa=d.mat4();class xa extends xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=va;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ba;if(l){const e=ya;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,wa),m=Ba,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Pa=d.vec3(),Ca=d.vec3(),Ma=d.vec3(),Ea=d.vec3(),Fa=d.mat4();class Ia extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Pa;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ca;if(l){const e=Ma;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Fa),m=Ea,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElements(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Da{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ma(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _a(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new xa(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ia(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Sa={};class Ta{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]}}class La{constructor(e){console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Sa[t];return i||(i=new Da(e),Sa[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Sa[t],i._destroy()}))),i}(e.model.scene),this.model=e.model,this._buffer=new Ta(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=hn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length/4,r=new Float32Array(s);let o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){const s=new Uint32Array(i.indices);e.indicesBuf=new je(t,t.ELEMENT_ARRAY_BUFFER,s,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}flushInitFlags(){this._setDeferredFlags()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2],A=t[3];for(let e=0;e0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Lines instancing color fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push(" float viewportWidth = uSAOParams[0];"),o.push(" float viewportHeight = uSAOParams[1];"),o.push(" float blendCutoff = uSAOParams[2];"),o.push(" float blendFactor = uSAOParams[3];"),o.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),o.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):o.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class ka extends Ra{drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}const Oa=d.vec3(),Na=d.vec3(),Qa=d.vec3();d.vec3();const Va=d.mat4();class Ha extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Oa;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Na;if(l){const e=d.transformPoint3(h,l,Qa);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Va),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ja=d.vec3(),Ga=d.vec3(),za=d.vec3();d.vec3();const Wa=d.mat4();class Ka extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=ja;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Ga;if(l){const e=d.transformPoint3(h,l,za);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Wa),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Xa{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}eagerCreateRenders(){this._snapInitRenderer||(this._snapInitRenderer=new Ha(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ka(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Ua(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ka(this._scene)),this._silhouetteRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Ha(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ka(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Ya={};const Ja=new Uint8Array(4),Za=new Float32Array(1),qa=new Float32Array(3),$a=new Float32Array(4);class el{constructor(e){console.info("VBOInstancingLinesLayer"),this.model=e.model,this.material=e.material,this.sortId="LinesInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Ya[t];return i||(i=new Xa(e),Ya[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Ya[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({obb:d.OBB3(),numInstances:0,origin:null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,e.origin&&(this._state.origin=d.vec3(e.origin)),this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let t=!1;this._state.colorsBuf=new je(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(r>0){let t=!1;this._state.flagsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,t)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){const s=new Uint8Array(i.colorsCompressed),r=!1;t.colorsBuf=new je(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,r)}if(i.positionsCompressed&&i.positionsCompressed.length>0){const s=!1;t.positionsBuf=new je(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,s),t.positionsDecodeMatrix=d.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new je(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Ja[0]=t[0],Ja[1]=t[1],Ja[2]=t[2],Ja[3]=t[3],this._state.colorsBuf.setData(Ja,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?255:0)<<16,Za[0]=d,this._state.flagsBuf.setData(Za,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qa[0]=t[0],qa[1]=t[1],qa[2]=t[2],this._state.offsetsBuf.setData(qa,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;$a[0]=t[0],$a[1]=t[4],$a[2]=t[8],$a[3]=t[12],this._state.modelMatrixCol0Buf.setData($a,i),$a[0]=t[1],$a[1]=t[5],$a[2]=t[9],$a[3]=t[13],this._state.modelMatrixCol1Buf.setData($a,i),$a[0]=t[2],$a[1]=t[6],$a[2]=t[10],$a[3]=t[14],this._state.modelMatrixCol2Buf.setData($a,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK)}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}class tl extends xo{_draw(e){const{gl:t}=this._scene.canvas,{state:i,frameCtx:s,incrementDrawState:r}=e;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}class il extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{incrementDrawState:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class sl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points batching silhouette vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("outColor = color;"),o.push("}"),o}}class rl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}class ol extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class nl extends tl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}const al=d.vec3(),ll=d.vec3(),Al=d.vec3(),hl=d.vec3(),cl=d.mat4();class ul extends xo{drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=al;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=ll;if(l){const e=Al;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,cl),m=hl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dl=d.vec3(),pl=d.vec3(),fl=d.vec3(),gl=d.vec3(),ml=d.mat4();class _l extends xo{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=dl;let g,m;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=pl;if(l){const e=fl;d.transformPoint3(h,l,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,ml),m=gl,m[0]=o.eye[0]-t[0],m[1]=o.eye[1]-t[1],m[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,m=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,m),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,_+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),n.drawArrays(n.POINTS,0,a.positionsBuf.numItems)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;const i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class vl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new il(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new sl(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new rl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new ol(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nl(this._scene)),this._occlusionRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new ul(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new _l(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const bl={};class yl{constructor(e=5e6){e>5e6&&(e=5e6),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]}}class Bl{constructor(e){console.info("Creating VBOBatchingPointsLayer"),this.model=e.model,this.sortId="PointsBatchingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=bl[t];return i||(i=new vl(e),bl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete bl[t],i._destroy()}))),i}(e.model.scene),this._buffer=new yl(e.maxGeometryBatchSize),this._scratchMemory=e.scratchMemory,this._state=new At({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:d.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=d.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,e.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(e.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,e.origin&&(this._state.origin=d.vec3(e.origin))}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){const s=new Uint16Array(i.positions);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=hn(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new je(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new je(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.STATIC_DRAW,r)}if(i.positions.length>0){const s=i.positions.length/3,r=new Float32Array(s);let o=!1;e.flagsBuf=new je(t,t.ARRAY_BUFFER,r,r.length,1,t.DYNAMIC_DRAW,o)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new je(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new je(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),n=t[0],a=t[1],l=t[2];for(let e=0;e0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Pl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){super.drawLayer(e,t,i,{colorUniform:!0})}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}class Cl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}class Ml extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}class El extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0;e 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0;e 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}class Fl extends wl{_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Points instancing depth vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),r)for(o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;"),i=0,s=t.getNumAllocatedSectionPlanes();i 1.0) {"),o.push(" discard;"),o.push(" }")),r){for(o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;"),i=0,s=t.getNumAllocatedSectionPlanes();i 0.0) { discard; }"),o.push("}")}return o.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}}class Il extends wl{_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}const Dl=d.vec3(),Sl=d.vec3(),Tl=d.vec3();d.vec3();const Ll=d.mat4();class Rl extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.canvas.gl,n=r.camera,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Dl;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=Sl;if(l){const e=d.transformPoint3(h,l,Tl);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Ll),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1)),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ul=d.vec3(),kl=d.vec3(),Ol=d.vec3();d.vec3();const Nl=d.mat4();class Ql extends xo{constructor(e){super(e,!1,{instancing:!0})}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=t.aabb,p=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));const f=Ul;let g;if(f[0]=d.safeInv(u[3]-u[0])*d.MAX_INT,f[1]=d.safeInv(u[4]-u[1])*d.MAX_INT,f[2]=d.safeInv(u[5]-u[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(f[0]),e.snapPickCoordinateScale[1]=d.safeInv(f[1]),e.snapPickCoordinateScale[2]=d.safeInv(f[2]),l||0!==A[0]||0!==A[1]||0!==A[2]){const t=kl;if(l){const e=d.transformPoint3(h,l,Ol);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=A[0],t[1]+=A[1],t[2]+=A[2],g=K(p,t,Nl),e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else g=p,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);let m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(g,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}_allocate(){super._allocate();const e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}_bindProgram(){this._program.bind()}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(let t=0;t> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Vl{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new xl(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Pl(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Fl(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Cl(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ml(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new El(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Il(this._scene)),this._shadowRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new Rl(this._scene,!1)),this._snapInitRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new Ql(this._scene)),this._snapRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}const Hl={};const jl=new Uint8Array(4),Gl=new Float32Array(1),zl=new Float32Array(3),Wl=new Float32Array(4);class Kl{constructor(e){console.info("VBOInstancingPointsLayer"),this.model=e.model,this.material=e.material,this.sortId="PointsInstancingLayer",this.layerIndex=e.layerIndex,this._renderers=function(e){const t=e.id;let i=Hl[t];return i||(i=new Vl(e),Hl[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Hl[t],i._destroy()}))),i}(e.model.scene),this._aabb=d.collapseAABB3(),this._state=new At({obb:d.OBB3(),numInstances:0,origin:e.origin?d.vec3(e.origin):null,geometry:e.geometry,positionsDecodeMatrix:e.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=e.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e0){let s=!1;i.flagsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;i.offsetsBuf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){const t=!1;i.positionsBuf=new je(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,t),i.positionsDecodeMatrix=d.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){const t=new Uint8Array(s.colorsCompressed),r=!1;i.colorsBuf=new je(e,e.ARRAY_BUFFER,t,t.length,4,e.STATIC_DRAW,r)}if(this._modelMatrixCol0.length>0){const t=!1;i.modelMatrixCol0Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),i.modelMatrixCol1Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),i.modelMatrixCol2Buf=new je(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;i.pickColorsBuf=new je(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}i.geometry=null,this._finalized=!0}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";jl[0]=t[0],jl[1]=t[1],jl[2]=t[2],this._state.colorsBuf.setData(jl,3*e)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(t&q),r=!!(t&se),o=!!(t&re),n=!!(t&oe),a=!!(t&ne),l=!!(t&ee),A=!!(t&$);let h,c;h=!s||A||r||o&&!this.model.scene.highlightMaterial.glowThrough||n&&!this.model.scene.selectedMaterial.glowThrough?mo.NOT_RENDERED:i?mo.COLOR_TRANSPARENT:mo.COLOR_OPAQUE,c=!s||A?mo.NOT_RENDERED:n?mo.SILHOUETTE_SELECTED:o?mo.SILHOUETTE_HIGHLIGHTED:r?mo.SILHOUETTE_XRAYED:mo.NOT_RENDERED;let u=0;u=!s||A?mo.NOT_RENDERED:n?mo.EDGES_SELECTED:o?mo.EDGES_HIGHLIGHTED:r?mo.EDGES_XRAYED:a?i?mo.EDGES_COLOR_TRANSPARENT:mo.EDGES_COLOR_OPAQUE:mo.NOT_RENDERED;let d=0;d|=h,d|=c<<4,d|=u<<8,d|=(s&&!A&&l?mo.PICK:mo.NOT_RENDERED)<<12,d|=(t&te?255:0)<<16,Gl[0]=d,this._state.flagsBuf.setData(Gl,e)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(zl[0]=t[0],zl[1]=t[1],zl[2]=t[2],this._state.offsetsBuf.setData(zl,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}setMatrix(e,t){if(!this._finalized)throw"Not finalized";const i=4*e;Wl[0]=t[0],Wl[1]=t[4],Wl[2]=t[8],Wl[3]=t[12],this._state.modelMatrixCol0Buf.setData(Wl,i),Wl[0]=t[1],Wl[1]=t[5],Wl[2]=t[9],Wl[3]=t[13],this._state.modelMatrixCol1Buf.setData(Wl,i),Wl[0]=t[2],Wl[1]=t[6],Wl[2]=t[10],Wl[3]=t[14],this._state.modelMatrixCol2Buf.setData(Wl,i)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,mo.PICK)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,mo.PICK)}drawPickNormals(e,t){}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK)}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK)}destroy(){const e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Xl=d.vec3(),Yl=d.vec3(),Jl=d.mat4();class Zl{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=Xl;if(g){const t=d.transformPoint3(c,A,Yl);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,Jl)}else f=p;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),n.drawArrays(n.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),n.drawArrays(n.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),n.drawArrays(n.LINES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class ql{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}eagerCreateRenders(){}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Zl(this._scene,!1)),this._colorRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy()}}const $l={};class eA{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]}}class tA{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindLineIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}class iA{constructor(e,t,i,s,r=null){this._gl=e,this._texture=t,this._textureWidth=i,this._textureHeight=s,this._textureData=r}bindTexture(e,t,i){return e.bindTexture(t,this,i)}bind(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}unbind(e){}}const sA={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(sA,null,4));let e=0;Object.keys(sA).forEach((t=>{t.startsWith("size")&&(e+=sA[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/sA.totalLines).toFixed(2)}`);let t={};Object.keys(sA).forEach((i=>{i.startsWith("size")&&(t[i]=`${(sA[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class rA{disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}generateTextureForColorsAndFlags(e,t,i,s,r){const o=t.length;this.numPortions=o;const n=4096,a=Math.ceil(o/512);if(0===a)throw"texture height===0";const l=new Uint8Array(16384*a);sA.sizeDataColorsAndFlags+=l.byteLength,sA.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),l.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20);const A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,n,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,A,n,a,l)}generateTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);sA.sizeDataTextureOffsets+=r.byteLength,sA.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,o,i,s,r)}generateTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);sA.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete $l[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new eA,this._dataTextureState=new tA,this._dataTextureGenerator=new rA,this._state=new At({origin:d.vec3(t.origin),textureState:this._dataTextureState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&sA.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/2})),(this._state.numVertices+s>4096*nA||t+r>4096*nA)&&sA.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*nA&&t+r<=4096*nA}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/2/8)*2;sA.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}const i=t.positionsCompressed,s=t.indices,r=this._buffer;r.positionsCompressed.push(i);const o=r.lenPositionsCompressed/3,n=i.length/3;let a;r.lenPositionsCompressed+=i.length;let l=0;if(s){let e;l=s.length/2,n<=256?(e=r.indices8Bits,a=r.lenIndices8Bits/2,r.lenIndices8Bits+=s.length):n<=65536?(e=r.indices16Bits,a=r.lenIndices16Bits/2,r.lenIndices16Bits+=s.length):(e=r.indices32Bits,a=r.lenIndices32Bits/2,r.lenIndices32Bits+=s.length),e.push(s)}this._state.numVertices+=n,sA.numberOfGeometries++;return{vertexBase:o,numVertices:n,numLines:l,indicesBase:a}}_createSubPortion(e,t){const i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,n=e.pickColor,a=this._buffer,l=this._state;a.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),a.perObjectInstancePositioningMatrices.push(o||cA),a.perObjectSolid.push(!!e.solid),s?a.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):i&&a.perObjectColors.push([i[0],i[1],i[2],r]),a.perObjectPickColors.push(n),a.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?l.numIndices8Bits:t.numVertices<=65536?l.numIndices16Bits:l.numIndices32Bits,a.perObjectIndexBaseOffsets.push(e/2-t.indicesBase)}const A=this._subPortions.length;if(t.numLines>0){let e,i=2*t.numLines;t.numVertices<=256?(e=a.perLineNumberPortionId8Bits,l.numIndices8Bits+=i,sA.totalLines8Bits+=t.numLines):t.numVertices<=65536?(e=a.perLineNumberPortionId16Bits,l.numIndices16Bits+=i,sA.totalLines16Bits+=t.numLines):(e=a.perLineNumberPortionId32Bits,l.numIndices32Bits+=i,sA.totalLines32Bits+=t.numLines),sA.totalLines+=t.numLines;for(let i=0;i0&&(t.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,lA))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),c.bindTexture(c.TEXTURE_2D,h.texturePerObjectColorsAndFlags._texture),c.texSubImage2D(c.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,c.RGBA_INTEGER,c.UNSIGNED_BYTE,lA))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,lA))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,AA))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,aA))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){}drawSilhouetteHighlighted(e,t){}drawSilhouetteSelected(e,t){}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}setPickMatrices(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawSnapInit(e,t){}drawSnap(e,t){}drawPickNormals(e,t){}destroy(){if(this._destroyed)return;const e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}const dA=d.vec3(),pA=d.vec3(),fA=d.vec3();d.vec3();const gA=d.vec4(),mA=d.mat4();class _A{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=dA;if(g){const t=d.transformPoint3(c,A,pA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,mA),f=fA,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new He(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e0;let r;const o=[];o.push("#version 300 es"),o.push("// TrianglesDataTextureColorRenderer vertex shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("precision highp usampler2D;"),o.push("precision highp isampler2D;"),o.push("precision highp sampler2D;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("precision mediump usampler2D;"),o.push("precision mediump isampler2D;"),o.push("precision mediump sampler2D;"),o.push("#endif"),o.push("uniform int renderPass;"),o.push("uniform mat4 sceneModelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),o.push("uniform highp sampler2D uTexturePerObjectMatrix;"),o.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),o.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),o.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),o.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),o.push("uniform vec3 uCameraEyeRtc;"),o.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("out float isPerspective;")),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e> 3) & 4095;"),o.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),o.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),o.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),o.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),o.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),o.push("if (int(flags.x) != renderPass) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("} else {"),o.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),o.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),o.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),o.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),o.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),o.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),o.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),o.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),o.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),o.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),o.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),o.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),o.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),o.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),o.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),o.push("if (color.a == 0u) {"),o.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),o.push(" return;"),o.push("};"),o.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),o.push("vec3 position;"),o.push("position = positions[gl_VertexID % 3];"),o.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),o.push("if (solid != 1u) {"),o.push("if (isPerspectiveMatrix(projMatrix)) {"),o.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),o.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("} else {"),o.push("if (viewNormal.z < 0.0) {"),o.push("position = positions[2 - (gl_VertexID % 3)];"),o.push("viewNormal = -viewNormal;"),o.push("}"),o.push("}"),o.push("}"),o.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),o.push("vec4 viewPosition = viewMatrix * worldPosition; "),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(let e=0,i=t.getNumAllocatedSectionPlanes();e 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vA=new Float32Array([1,1,1]),bA=d.vec3(),yA=d.vec3(),BA=d.vec3();d.vec3();const wA=d.mat4();class xA{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o,p=r.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=bA;if(A){const t=yA;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,wA),g=BA,g[0]=r.eye[0]-e[0],g[1]=r.eye[1]-e[1],g[2]=r.eye[2]-e[2]}else f=p,g=r.eye;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===mo.SILHOUETTE_XRAYED){const e=s.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.SILHOUETTE_HIGHLIGHTED){const e=s.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.SILHOUETTE_SELECTED){const e=s.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,vA);if(s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,r=o.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const PA=new Float32Array([0,0,0,1]),CA=d.vec3(),MA=d.vec3();d.vec3();const EA=d.mat4();class FA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=CA;if(g){const t=d.transformPoint3(c,A,MA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,EA)}else f=p;if(n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),i===mo.EDGES_XRAYED){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.EDGES_HIGHLIGHTED){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(i===mo.EDGES_SELECTED){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;n.uniform4f(this._uColor,t[0],t[1],t[2],i)}else n.uniform4fv(this._uColor,PA);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const IA=d.vec3(),DA=d.vec3(),SA=d.mat4();class TA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=o.viewMatrix;if(!this._program&&(this._allocate(),this.errors))return;let f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=IA;if(g){const t=d.transformPoint3(c,A,DA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,SA)}else f=p;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(n.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(n.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(n.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const LA=d.vec3(),RA=d.vec3(),UA=d.vec3(),kA=d.mat4();class OA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s;let p,f;l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=LA;if(g){const t=d.transformPoint3(c,A,RA);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(o.viewMatrix,e,kA),f=UA,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=o.viewMatrix,f=o.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,e)}const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const NA=d.vec3(),QA=d.vec3(),VA=d.vec3();d.vec3();const HA=d.mat4();class jA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;let f,g;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const t=NA;if(A){const e=QA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],f=K(p,t,HA),g=VA,g[0]=o.eye[0]-t[0],g[1]=o.eye[1]-t[1],g[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else f=p,g=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniform1f(this._uPickZNear,e.pickZNear),n.uniform1f(this._uPickZFar,e.pickZFar),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const GA=d.vec3(),zA=d.vec3(),WA=d.vec3(),KA=d.vec3();d.vec3();const XA=d.mat4();class YA{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=GA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=zA;if(v){const e=d.transformPoint3(c,A,WA);t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,XA),_=KA,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),n.drawArrays(w,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),n.drawArrays(w,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),n.drawArrays(w,0,a.numEdgeIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const JA=d.vec3(),ZA=d.vec3(),qA=d.vec3(),$A=d.vec3();d.vec3();const eh=d.mat4();class th{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=t.aabb,f=e.pickViewMatrix||o.viewMatrix,g=JA;let m,_;g[0]=d.safeInv(p[3]-p[0])*d.MAX_INT,g[1]=d.safeInv(p[4]-p[1])*d.MAX_INT,g[2]=d.safeInv(p[5]-p[2])*d.MAX_INT,e.snapPickCoordinateScale[0]=d.safeInv(g[0]),e.snapPickCoordinateScale[1]=d.safeInv(g[1]),e.snapPickCoordinateScale[2]=d.safeInv(g[2]),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const v=0!==A[0]||0!==A[1]||0!==A[2],b=0!==h[0]||0!==h[1]||0!==h[2];if(v||b){const t=ZA;if(v){const e=qA;d.transformPoint3(c,A,e),t[0]=e[0],t[1]=e[1],t[2]=e[2]}else t[0]=0,t[1]=0,t[2]=0;t[0]+=h[0],t[1]+=h[1],t[2]+=h[2],m=K(f,t,eh),_=$A,_[0]=o.eye[0]-t[0],_[1]=o.eye[1]-t[1],_[2]=o.eye[2]-t[2],e.snapPickOrigin[0]=t[0],e.snapPickOrigin[1]=t[1],e.snapPickOrigin[2]=t[2]}else m=f,_=o.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform3fv(this._uCameraEyeRtc,_),n.uniform2fv(this._uVectorA,e.snapVectorA),n.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,g),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible),n.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,m),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);{const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),B=r._sectionPlanesState.sectionPlanes.length;if(y>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*B,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(`outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ih=d.vec3(),sh=d.vec3(),rh=d.vec3();d.vec3();const oh=d.mat4();class nh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=s,p=e.pickViewMatrix||o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let f,g;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),A||0!==h[0]||0!==h[1]||0!==h[2]){const e=ih;if(A){const t=sh;d.transformPoint3(c,A,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],f=K(p,e,oh),g=rh,g[0]=o.eye[0]-e[0],g[1]=o.eye[1]-e[1],g[2]=o.eye[2]-e[2]}else f=p,g=o.eye;n.uniform3fv(this._uCameraEyeRtc,g),n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,f),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix);const m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0;t 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ah=d.vec3(),lh=d.vec3(),Ah=d.vec3();d.vec3();const hh=d.mat4();class ch{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=ah;if(g){const t=d.transformPoint3(c,A,lh);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,hh),f=Ah,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const uh=d.vec3(),dh=d.vec3(),ph=d.vec3();d.vec3();const fh=d.mat4();class gh{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,n=r.canvas.gl,a=t._state,l=t._state.origin,{position:A,rotationMatrix:h,rotationMatrixConjugate:c}=s,u=o.viewMatrix;if(!this._program&&(this._allocate(t),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));const g=0!==l[0]||0!==l[1]||0!==l[2],m=0!==A[0]||0!==A[1]||0!==A[2];if(g||m){const e=uh;if(g){const t=dh;d.transformPoint3(h,l,t),e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=A[0],e[1]+=A[1],e[2]+=A[2],p=K(u,e,fh),f=ph,f[0]=o.eye[0]-e[0],f[1]=o.eye[1]-e[1],f[2]=o.eye[2]-e[2]}else p=u,f=o.eye;n.uniform1i(this._uRenderPass,i),n.uniformMatrix4fv(this._uWorldMatrix,!1,c),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,o.projMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),n.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),v=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(Te.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(let t=0;t 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&Te.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const mh=d.vec3(),_h=d.vec3(),vh=d.vec3();d.vec3(),d.vec4();const bh=d.mat4();class yh{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,n=s.canvas.gl,a=t._state,l=a.textureState,A=t._state.origin,{position:h,rotationMatrix:c,rotationMatrixConjugate:u}=o;if(!this._program&&(this._allocate(),this.errors))return;let p,f;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);const g=0!==A[0]||0!==A[1]||0!==A[2],m=0!==h[0]||0!==h[1]||0!==h[2];if(g||m){const e=mh;if(g){const t=d.transformPoint3(c,A,_h);e[0]=t[0],e[1]=t[1],e[2]=t[2]}else e[0]=0,e[1]=0,e[2]=0;e[0]+=h[0],e[1]+=h[1],e[2]+=h[2],p=K(r.viewMatrix,e,bh),f=vh,f[0]=r.eye[0]-e[0],f[1]=r.eye[1]-e[1],f[2]=r.eye[2]-e[2]}else p=r.viewMatrix,f=r.eye;if(n.uniform2fv(this._uPickClipPos,e.pickClipPos),n.uniform2f(this._uDrawingBufferSize,n.drawingBufferWidth,n.drawingBufferHeight),n.uniformMatrix4fv(this._uSceneModelMatrix,!1,u),n.uniformMatrix4fv(this._uViewMatrix,!1,p),n.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),n.uniform3fv(this._uCameraEyeRtc,f),n.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,t)}const _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),v=s._sectionPlanesState.sectionPlanes.length;if(_>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*v,r=o.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t];if(s)if(t0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),n.drawArrays(n.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),n.drawArrays(n.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),n.drawArrays(n.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new He(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(let t=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();t 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(` outNormal = ivec4(worldNormal * float(${d.MAX_INT}), 1.0);`),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Bh{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}eagerCreateRenders(){this._silhouetteRenderer||(this._silhouetteRenderer=new xA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new OA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new jA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new yh(this._scene)),this._snapRenderer||(this._snapRenderer=new YA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new th(this._scene)),this._snapRenderer||(this._snapRenderer=new YA(this._scene))}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new _A(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new _A(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new xA(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ch(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new gh(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new FA(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new TA(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new OA(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new yh(this._scene)),this._pickNormalsRenderer}get pickNormalsFlatRenderer(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new yh(this._scene)),this._pickNormalsFlatRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new jA(this._scene)),this._pickDepthRenderer}get snapRenderer(){return this._snapRenderer||(this._snapRenderer=new YA(this._scene)),this._snapRenderer}get snapInitRenderer(){return this._snapInitRenderer||(this._snapInitRenderer=new th(this._scene)),this._snapInitRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new nh(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const wh={};class xh{constructor(){this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]}}class Ph{constructor(){this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}finalize(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}bindCommonTextures(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}bindTriangleIndicesTextures(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}bindEdgeIndicesTextures(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}const Ch={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ch,null,4));let e=0;Object.keys(Ch).forEach((t=>{t.startsWith("size")&&(e+=Ch[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/Ch.totalPolygons).toFixed(2)}`);let t={};Object.keys(Ch).forEach((i=>{i.startsWith("size")&&(t[i]=`${(Ch[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};class Mh{constructor(){}disableBindedTextureFiltering(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}createTextureForColorsAndFlags(e,t,i,s,r,o,n){const a=t.length;this.numPortions=a;const l=4096,A=Math.ceil(a/512);if(0===A)throw"texture height===0";const h=new Uint8Array(16384*A);Ch.sizeDataColorsAndFlags+=h.byteLength,Ch.numberOfTextures++;for(let e=0;e>24&255,s[e]>>16&255,s[e]>>8&255,255&s[e]],32*e+16),h.set([r[e]>>24&255,r[e]>>16&255,r[e]>>8&255,255&r[e]],32*e+20),h.set([o[e]>>24&255,o[e]>>16&255,o[e]>>8&255,255&o[e]],32*e+24),h.set([n[e]?1:0,0,0,0],32*e+28);const c=e.createTexture();return e.bindTexture(e.TEXTURE_2D,c),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,A),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,A,e.RGBA_INTEGER,e.UNSIGNED_BYTE,h,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,c,l,A,h)}createTextureForObjectOffsets(e,t){const i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";const r=new Float32Array(1536*s).fill(0);Ch.sizeDataTextureOffsets+=r.byteLength,Ch.numberOfTextures++;const o=e.createTexture();return e.bindTexture(e.TEXTURE_2D,o),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new iA(e,o,i,s,r)}createTextureForInstancingMatrices(e,t){const i=t.length;if(0===i)throw"num instance matrices===0";const s=2048,r=Math.ceil(i/512),o=new Float32Array(8192*r);Ch.numberOfTextures++;for(let e=0;e{i._compile(),i.eagerCreateRenders()})),e.on("destroyed",(()=>{delete wh[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new xh,this._dtxState=new Ph,this._dtxTextureFactory=new Mh,this._state=new At({origin:d.vec3(t.origin),metallicRoughnessBuf:null,textureState:this._dtxState,numIndices8Bits:0,numIndices16Bits:0,numIndices32Bits:0,numEdgeIndices8Bits:0,numEdgeIndices16Bits:0,numEdgeIndices32Bits:0,numVertices:0}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._subPortions=[],this._portionToSubPortionsMap=[],this._bucketGeometries={},this._meshes=[],this._aabb=d.collapseAABB3(),this.aabbDirty=!0,this._numUpdatesInFrame=0,this._finalized=!1}get aabb(){if(this.aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._meshes.length;e65536&&Ch.cannotCreatePortion.because10BitsObjectId++;let i=this._numPortions+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits);let s=0,r=0;e.buckets.forEach((e=>{s+=e.positionsCompressed.length/3,r+=e.indices.length/3})),(this._state.numVertices+s>4096*Fh||t+r>4096*Fh)&&Ch.cannotCreatePortion.becauseTextureSize++,i&&=this._state.numVertices+s<=4096*Fh&&t+r<=4096*Fh}return i}createPortion(e,t){if(this._finalized)throw"Already finalized";const i=[];t.buckets.forEach(((e,s)=>{const r=void 0!==t.geometryId&&null!==t.geometryId?`${t.geometryId}#${s}`:`${t.id}#${s}`;let o=this._bucketGeometries[r];o||(o=this._createBucketGeometry(t,e),this._bucketGeometries[r]=o);const n=this._createSubPortion(t,o,e);i.push(n)}));const s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(i),this.model.numPortions++,this._meshes.push(e),s}_createBucketGeometry(e,t){if(t.indices){const e=8*Math.ceil(t.indices.length/3/8)*3;Ch.overheadSizeAlignementIndices+=2*(e-t.indices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.indices),t.indices=i}if(t.edgeIndices){const e=8*Math.ceil(t.edgeIndices.length/2/8)*2;Ch.overheadSizeAlignementEdgeIndices+=2*(e-t.edgeIndices.length);const i=new Uint32Array(e);i.fill(0),i.set(t.edgeIndices),t.edgeIndices=i}const i=t.positionsCompressed,s=t.indices,r=t.edgeIndices,o=this._buffer;o.positionsCompressed.push(i);const n=o.lenPositionsCompressed/3,a=i.length/3;let l;o.lenPositionsCompressed+=i.length;let A,h=0;if(s){let e;h=s.length/3,a<=256?(e=o.indices8Bits,l=o.lenIndices8Bits/3,o.lenIndices8Bits+=s.length):a<=65536?(e=o.indices16Bits,l=o.lenIndices16Bits/3,o.lenIndices16Bits+=s.length):(e=o.indices32Bits,l=o.lenIndices32Bits/3,o.lenIndices32Bits+=s.length),e.push(s)}let c=0;if(r){let e;c=r.length/2,a<=256?(e=o.edgeIndices8Bits,A=o.lenEdgeIndices8Bits/2,o.lenEdgeIndices8Bits+=r.length):a<=65536?(e=o.edgeIndices16Bits,A=o.lenEdgeIndices16Bits/2,o.lenEdgeIndices16Bits+=r.length):(e=o.edgeIndices32Bits,A=o.lenEdgeIndices32Bits/2,o.lenEdgeIndices32Bits+=r.length),e.push(r)}this._state.numVertices+=a,Ch.numberOfGeometries++;return{vertexBase:n,numVertices:a,numTriangles:h,numEdges:c,indicesBase:l,edgeIndicesBase:A}}_createSubPortion(e,t,i,s){const r=e.color;e.metallic,e.roughness;const o=e.colors,n=e.opacity,a=e.meshMatrix,l=e.pickColor,A=this._buffer,h=this._state;A.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),A.perObjectInstancePositioningMatrices.push(a||Lh),A.perObjectSolid.push(!!e.solid),o?A.perObjectColors.push([255*o[0],255*o[1],255*o[2],255]):r&&A.perObjectColors.push([r[0],r[1],r[2],n]),A.perObjectPickColors.push(l),A.perObjectVertexBases.push(t.vertexBase);{let e;e=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,A.perObjectIndexBaseOffsets.push(e/3-t.indicesBase)}{let e;e=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,A.perObjectEdgeIndexBaseOffsets.push(e/2-t.edgeIndicesBase)}const c=this._subPortions.length;if(t.numTriangles>0){let e,i=3*t.numTriangles;t.numVertices<=256?(e=A.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=i,Ch.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(e=A.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=i,Ch.totalPolygons16Bits+=t.numTriangles):(e=A.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=i,Ch.totalPolygons32Bits+=t.numTriangles),Ch.totalPolygons+=t.numTriangles;for(let i=0;i0){let e,i=2*t.numEdges;t.numVertices<=256?(e=A.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=i,Ch.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(e=A.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=i,Ch.totalEdges16Bits+=t.numEdges):(e=A.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=i,Ch.totalEdges32Bits+=t.numEdges),Ch.totalEdges+=t.numEdges;for(let i=0;i0&&(t.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(t.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(t.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(i,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(t.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(i,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(t.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(i,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(t.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(i,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(t.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(i,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(t.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(i,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(t.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(i,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),t.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(()=>{this._deferredSetFlagsDirty&&this._uploadDeferredFlags(),this._numUpdatesInFrame=0}))}isEmpty(){return 0===this._numPortions}initFlags(e,t,i){t&q&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&re&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&se&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&oe&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&te&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&ne&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&ee&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&$&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}flushInitFlags(){this._setDeferredFlags(),this._setDeferredFlags2()}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";t&q?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&re?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&se?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&oe?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&ne?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&te?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}_beginDeferredFlags(){this._deferredSetFlagsActive=!0}_uploadDeferredFlags(){if(this._deferredSetFlagsActive=!1,!this._deferredSetFlagsDirty)return;this._deferredSetFlagsDirty=!1;const e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";t&$?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";t&ee?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,Dh)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i,s=!1){const r=this._portionToSubPortionsMap[e];for(let e=0,o=r.length;e=10&&this._beginDeferredFlags(),g.bindTexture(g.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),g.texSubImage2D(g.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,g.RGBA_INTEGER,g.UNSIGNED_BYTE,Dh))}_setDeferredFlags(){}_setFlags2(e,t,i=!1){const s=this._portionToSubPortionsMap[e];for(let e=0,r=s.length;e=10&&this._beginDeferredFlags(),o.bindTexture(o.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),o.texSubImage2D(o.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,o.RGBA_INTEGER,o.UNSIGNED_BYTE,Dh))}_setDeferredFlags2(){}setOffset(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,Sh))}setMatrix(e,t){const i=this._portionToSubPortionsMap[e];for(let e=0,s=i.length;e=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Ih))}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,mo.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}_updateBackfaceCull(e,t){const i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,mo.COLOR_TRANSPARENT))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_XRAYED))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_HIGHLIGHTED))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,mo.SILHOUETTE_SELECTED))}drawEdgesColorOpaque(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,mo.EDGES_COLOR_OPAQUE)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,mo.EDGES_COLOR_TRANSPARENT)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_HIGHLIGHTED)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_SELECTED)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,mo.EDGES_XRAYED)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,mo.COLOR_OPAQUE))}setPickMatrices(e,t){}drawPickMesh(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,mo.PICK))}drawPickDepths(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,mo.PICK))}drawSnapInit(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,mo.PICK))}drawSnap(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,mo.PICK))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,mo.PICK))}destroy(){if(this._destroyed)return;const e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}class Uh{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 kh{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const Oh={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 Nh{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==Hh[e])return void Hh[e].push({onLoad:t,onProgress:i,onError:s});Hh[e]=[],Hh[e].push({onLoad:t,onProgress:i,onError:s});const o=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),n=this.mimeType,a=this.responseType;fetch(o).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=Hh[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),o=r?parseInt(r):0,n=0!==o;let a=0;const l=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{a+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:n,loaded:a,total:o});for(let e=0,t=i.length;e{switch(a){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,n)));case"json":return e.json();default:if(void 0===n)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(n),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{Oh.add(e,t);const i=Hh[e];delete Hh[e];for(let e=0,s=i.length;e{const i=Hh[e];if(void 0===i)throw this.manager.itemError(e),t;delete Hh[e];for(let e=0,s=i.length;e{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class Gh{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let zh=0;class Wh{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new Gh,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new jh;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new jh;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=Wh.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(Wh.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(Wh.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(Wh.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),zh>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),zh++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const o=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e))).then((e=>{const i=e.data,{mipmaps:o,width:n,height:a,format:l,type:A,error:h,dfdTransferFn:c,dfdFlags:u}=i;if("error"===A)return r(h);t.setCompressedData({mipmaps:o,props:{format:l,minFilter:1===o.length?1006:1008,magFilter:1===o.length?1006:1008,encoding:2===c?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),zh--}}Wh.BasisFormat={ETC1S:0,UASTC_4x4:1},Wh.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},Wh.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},Wh.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,o=_BasisFormat;self.addEventListener("message",(function(n){const h=n.data;switch(h.type){case"init":e=h.config,c=h.transcoderBinary,t=new Promise((e=>{i={wasmBinary:c,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:n,hasAlpha:c,mipmaps:u,format:d,dfdTransferFn:p,dfdFlags:f}=function(t){const n=new i.KTX2File(new Uint8Array(t));function h(){n.close(),n.delete()}if(!n.isValid())throw h(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const c=n.isUASTC()?o.UASTC_4x4:o.ETC1S,u=n.getWidth(),d=n.getHeight(),p=n.getLevels(),f=n.getHasAlpha(),g=n.getDFDTransferFunc(),m=n.getDFDFlags(),{transcoderFormat:_,engineFormat:v}=function(t,i,n,h){let c,u;const d=t===o.ETC1S?a:l;for(let s=0;s{delete Kh[t],i.destroy()}))),i} /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT @@ -14,7 +14,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){ /** * @author https://github.com/tmarti, with support from https://tribia.com/ * @license MIT - **/let $h=null;function ec(e,t){const i=3*e,s=3*t;let r,o,n,a,l,A;const h=Math.min(r=$h[i],o=$h[i+1],n=$h[i+2]),c=Math.min(a=$h[s],l=$h[s+1],A=$h[s+2]);if(h!==c)return h-c;const u=Math.max(r,o,n),d=Math.max(a,l,A);return u!==d?u-d:0}let tc=null;function ic(e,t){let i=tc[2*e]-tc[2*t];return 0!==i?i:tc[2*e+1]-tc[2*t+1]}function sc(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e>t;i.sort(ec);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}tc=new Int32Array(e),t.sort(ic);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new kh({id:"defaultColorTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new kh({id:"defaultMetalRoughTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new kh({id:"defaultNormalsTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new kh({id:"defaultEmissiveTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new kh({id:"defaultOcclusionTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Uh({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||_c),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new kh({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new Uh({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new cc({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||fc,i=e.position||gc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",pc),e.meshMatrix=d.composeMat4(i,pc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||mc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=cn(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):vc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];Y(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=hn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Ht.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new fa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new fa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new el({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Kl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=q),this._pickable&&!1!==e.pickable&&(t|=ee),this._culled&&!1!==e.culled&&(t|=$),this._clippable&&!1!==e.clippable&&(t|=te),this._collidable&&!1!==e.collidable&&(t|=ie),this._edges&&!1!==e.edges&&(t|=ne),this._xrayed&&!1!==e.xrayed&&(t|=se),this._highlighted&&!1!==e.highlighted&&(t|=re),this._selected&&!1!==e.selected&&(t|=oe),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Bc extends L{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,B=v.filter((e=>!b[e])),w=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=Fc(e.location,wc),i=Fc(e.direction,wc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=Dc(t),i=Dc(i)),new Br(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new Bc(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=Fc(e.location,xc),n=Fc(e.normal,Pc),a=Fc(e.up,Cc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Dc(o),n=Dc(n),a=Dc(a)),new Ao(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=Fc(e.perspective_camera.camera_view_point,wc),A=Fc(e.perspective_camera.camera_direction,wc),h=Fc(e.perspective_camera.camera_up_vector,wc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=Fc(e.orthogonal_camera.camera_view_point,wc),A=Fc(e.orthogonal_camera.camera_direction,wc),h=Fc(e.orthogonal_camera.camera_up_vector,wc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=Dc(a),A=Dc(A),h=Dc(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,wc)}else A=d.addVec3(a,A,wc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function Ec(e){return{x:e[0],y:e[1],z:e[2]}}function Fc(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ic(e){return new Float64Array([e[0],-e[2],e[1]])}function Dc(e){return new Float64Array([e[0],e[2],-e[1]])}const Sc=d.vec3(),Tc=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Lc extends L{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ue(i,t.origin),this._targetMarker=new ue(i,t.target),this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new pe(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new pe(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new pe(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new pe(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new ge(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new ge(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new ge(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new ge(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this.useRotationAdjustment=t.useRotationAdjustment}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;ue.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&c(e.offsetParent)),u=d.vec2();this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,u),this._markerDiv.style.left=u[0]-5+"px",this._markerDiv.style.top=u[1]-5+"px"):(this._markerDiv.style.left=c(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class kc extends z{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Uc(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Lc(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisibld:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const r=i.touches.length;if(1!==r||1!==i.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const n=i.touches[0],l=n.clientX,h=n.clientY;if(n.identifier!==A)return;let c,u;switch(a.set([l,h]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),c=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),c&&c.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=c.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(c.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=c.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:c.worldPos,entity:c.entity},target:{worldPos:c.worldPos,entity:c.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(u=t.pick({canvasPos:a,pickSurface:!0}),u&&u.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=u.canvasPos,this.pointerLens.snapped=!1),s.set(u.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=u.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:u.worldPos,entity:u.entity},target:{worldPos:u.worldPos,entity:u.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==r&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),c=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=c.worldPos,this._currentDistanceMeasurement.target.entity=c.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(u=t.pick({canvasPos:a,pickSurface:!0}),u&&u.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=u.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=u.worldPos,this._currentDistanceMeasurement.target.entity=u.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class Qc{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Vc{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Hc(e,i);return s?t?jc(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Hc(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=jc(r,[t]),i&&(r=jc(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Hc(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class zc extends Gc{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const Wc=d.vec3();class Kc extends L{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new zc(this),this._lookCurve=new zc(this),this._upCurve=new zc(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Wc),t.look=this._lookCurve.getPoint(e,Wc),t.up=this._upCurve.getPoint(e,Wc)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?$c._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,qc),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,Jc),s.look=d.subVec3(Jc,qc,Yc)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Yc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Zc)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,Jc),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Yc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Zc)),this._projection2){const t="ortho"===this._projection2?$c._easeOutExpo(e,0,1,1):$c._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class eu extends L{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new $c(this),this._t=0,this.state=eu.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case eu.SCRUBBING:return;case eu.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=eu.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case eu.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=eu.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=eu.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=eu.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=eu.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=eu.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=eu.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=eu.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}eu.STOPPED=0,eu.SCRUBBING=1,eu.PLAYING=2,eu.PLAYING_TO=3;const tu=d.vec3(),iu=d.vec3();d.vec3();const su=d.vec3([0,-1,0]),ru=d.vec4([0,0,0,1]);class ou extends L{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new Xr(this),this._plane=new fr(this,{geometry:new zt(this,oo({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Jt(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 fr(this,{geometry:new zt(this,ro({size:1,divisions:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Sr(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]),X(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,tu);const s=-d.dotVec3(i,tu);d.normalizeVec3(i),d.mulVec3Scalar(i,s,iu),d.vec3PairToQuaternion(su,e,ru),this._node.quaternion=ru}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class nu extends Dt{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new At({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new st(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function au(e){if(!lu(e.width)||!lu(e.height)){const t=document.createElement("canvas");t.width=Au(e.width),t.height=Au(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function lu(e){return 0==(e&e-1)}function Au(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class hu extends L{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new At({texture:new Hr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class pu{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const fu=d.vec3();class gu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class bu extends Gc{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class Bu extends bc{constructor(e,t={}){super(e,t)}}class wu extends L{constructor(e,t={}){super(e,t),this._skyboxMesh=new fr(this,{geometry:new zt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Jt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Xr(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class xu{transcode(e,t,i={}){}destroy(){}}const Pu=d.vec4(),Cu=d.vec4(),Mu=d.vec3(),Eu=d.vec3(),Fu=d.vec3(),Iu=d.vec4(),Du=d.vec4(),Su=d.vec4();class Tu{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,Mu);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),X(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new qr(this._scene,_r({radius:s})),this._pivotSphere=new fr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(X(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Lu)),i=d.cross3Vec3(t,e.worldUp,Ru);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=ku;t.project.unproject(e,a,Ou,Nu,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,Lu)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Ru),Uu);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Vu{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Re;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Hu=d.vec2();class ju{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,c=o[2],u=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/u,r.panDeltaY+=1.5*y*i/u}else r.panDeltaX+=.5*t.ortho.scale*(b/u),r.panDeltaY+=.5*t.ortho.scale*(y/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/c*i.dragRotationRate/2,r.rotateDeltaX+=y/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/c*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/u*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Hu);const i=Hu[0],s=Hu[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Hu,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,Gu);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Yu.orthoScale=g,n?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldRight,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):a?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldForward,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):l?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldRight,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):A?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldForward,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):h?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldUp,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,Wu),Ku))):c&&(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldUp,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,Wu)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Gu),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Yu,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Yu),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Zu{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class qu{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const $u=d.vec3();class ed{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,$u)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{id(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(id(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function id(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const sd=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class rd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(sd(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){sd(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];sd(t,l),sd(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,od(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(od(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(od(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Vu(this,this._configs),pivotController:new Qu(i,this._configs),panController:new Tu(i),cameraFlight:new $c(this,{duration:.5})},this._handlers=[new td(this.scene,this._controllers,this._configs,this._states,this._updates),new rd(this.scene,this._controllers,this._configs,this._states,this._updates),new ju(this.scene,this._controllers,this._configs,this._states,this._updates),new Ju(this.scene,this._controllers,this._configs,this._states,this._updates),new Zu(this.scene,this._controllers,this._configs,this._states,this._updates),new nd(this.scene,this._controllers,this._configs,this._states,this._updates),new qu(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ed(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?dd(t):null,n=i&&i.length>0?dd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r>t;i.sort(ec);const s=new Int32Array(e.length);for(let t=0,r=i.length;te[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}tc=new Int32Array(e),t.sort(ic);const i=new Int32Array(e.length);for(let s=0,r=t.length;st){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(o.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(o[2*e],o[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const a=new Int32Array(o.length/2);a.fill(0);const l=s.length/3;if(l>8*(1<u.maxNumPositions&&(u=c()),u.bucketNumber>8)return[e];let p;-1===A[l]&&(A[l]=u.numPositions++,u.positionsCompressed.push(s[3*l]),u.positionsCompressed.push(s[3*l+1]),u.positionsCompressed.push(s[3*l+2])),-1===A[h]&&(A[h]=u.numPositions++,u.positionsCompressed.push(s[3*h]),u.positionsCompressed.push(s[3*h+1]),u.positionsCompressed.push(s[3*h+2])),-1===A[d]&&(A[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(A[l]),u.indices.push(A[h]),u.indices.push(A[d]),(p=n(l,h))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(l,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]])),(p=n(h,d))>=0&&0===a[p]&&(a[p]=1,u.edgeIndices.push(A[o[2*p]]),u.edgeIndices.push(A[o[2*p+1]]))}const d=t/8*2,p=t/8,f=2*s.length+(r.length+o.length)*d;let g=0,m=-s.length/3;return h.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*p,m+=e.positionsCompressed.length/3})),g>f?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,o=e.edgeIndices,n=e.positionsCompressed;for(let e=0,s=t.length;e0){const e=t._meshes;for(let t=0,i=e.length;t0){const e=this._meshes;for(let t=0,i=e.length;t{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()})),this._createDefaultTextureSet(),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}_createDefaultTextureSet(){const e=new kh({id:"defaultColorTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new kh({id:"defaultMetalRoughTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new kh({id:"defaultNormalsTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new kh({id:"defaultEmissiveTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new kh({id:"defaultOcclusionTexture",texture:new Hr({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Uh({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||_c),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}get rotationMatrixConjugate(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e{l.setImage(A,{minFilter:i,magFilter:s,wrapS:r,wrapT:o,wrapR:n,flipY:e.flipY,encoding:a}),this.glRedraw()},A.src=e.src;break;default:this._textureTranscoder?y.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,l).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new kh({id:t,texture:l})}createTextureSet(e){const t=e.id;if(null==t)return void this.error("[createTextureSet] Config missing: id");if(this._textureSets[t])return void this.error(`[createTextureSet] Texture set already created: ${t}`);let i,s,r,o,n;if(void 0!==e.colorTextureId&&null!==e.colorTextureId){if(i=this._textures[e.colorTextureId],!i)return void this.error(`[createTextureSet] Texture not found: ${e.colorTextureId} - ensure that you create it first with createTexture()`)}else i=this._textures.defaultColorTexture;if(void 0!==e.metallicRoughnessTextureId&&null!==e.metallicRoughnessTextureId){if(s=this._textures[e.metallicRoughnessTextureId],!s)return void this.error(`[createTextureSet] Texture not found: ${e.metallicRoughnessTextureId} - ensure that you create it first with createTexture()`)}else s=this._textures.defaultMetalRoughTexture;if(void 0!==e.normalsTextureId&&null!==e.normalsTextureId){if(r=this._textures[e.normalsTextureId],!r)return void this.error(`[createTextureSet] Texture not found: ${e.normalsTextureId} - ensure that you create it first with createTexture()`)}else r=this._textures.defaultNormalsTexture;if(void 0!==e.emissiveTextureId&&null!==e.emissiveTextureId){if(o=this._textures[e.emissiveTextureId],!o)return void this.error(`[createTextureSet] Texture not found: ${e.emissiveTextureId} - ensure that you create it first with createTexture()`)}else o=this._textures.defaultEmissiveTexture;if(void 0!==e.occlusionTextureId&&null!==e.occlusionTextureId){if(n=this._textures[e.occlusionTextureId],!n)return void this.error(`[createTextureSet] Texture not found: ${e.occlusionTextureId} - ensure that you create it first with createTexture()`)}else n=this._textures.defaultOcclusionTexture;const a=new Uh({id:t,model:this,colorTexture:i,metallicRoughnessTexture:s,normalsTexture:r,emissiveTexture:o,occlusionTexture:n});return this._textureSets[t]=a,a}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new cc({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;if(!(void 0!==e.geometryId)){if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"!==e.primitive&&"lines"!==e.primitive&&"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)return this.error(`Unsupported value for 'primitive': '${primitive}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive)){const t=(e.positions||e.positionsCompressed).length/3;e.indices=this._createDefaultIndices(t)}if(!e.buckets&&!e.indices&&"points"!==e.primitive)return e.indices=this._createDefaultIndices(numIndices),this.error(`Param expected: indices (required for '${e.primitive}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;const t=!(!this._dtxEnabled||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||e.textureSetId);if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||fc,i=e.position||gc;e.rotation?(d.eulerToQuaternion(e.rotation,"XYZ",pc),e.meshMatrix=d.composeMat4(i,pc,t,d.mat4())):e.meshMatrix=d.composeMat4(i,e.quaternion||mc,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=cn(e.positionsDecodeBoundary,d.mat4())),t){if(e.type=2,e.color=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):vc,e.opacity=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,e.positions){const t=d.vec3(),i=[];Y(e.positions,i,t)&&(e.positions=i,e.origin=d.addVec3(e.origin,t,t))}if(e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=hn(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),Ht.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.buckets){const t=d.collapseAABB3();for(let i=0,s=e.buckets.length;i>24&255,r=i>>16&255,o=i>>8&255,n=255&i;switch(e.pickColor=new Uint8Array([n,o,r,s]),e.solid="solid"===e.primitive,t.origin=d.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i>>0).toString(16)}_getVBOInstancingLayer(e){const t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,o=`${Math.round(i[0])}.${Math.round(i[1])}.${Math.round(i[2])}.${s}.${r}`;let n=this._vboInstancingLayers[o];if(n)return n;let a=e.textureSet;const l=e.geometry;for(;!n;)switch(l.primitive){case"triangles":case"surface":n=new fa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":n=new fa({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":n=new el({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":n=new Kl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[o]=n,this.layerList.push(n),n}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return void this.error("Config missing: meshIds");let t=0;this._visible&&!1!==e.visible&&(t|=q),this._pickable&&!1!==e.pickable&&(t|=ee),this._culled&&!1!==e.culled&&(t|=$),this._clippable&&!1!==e.clippable&&(t|=te),this._collidable&&!1!==e.collidable&&(t|=ie),this._edges&&!1!==e.edges&&(t|=ne),this._xrayed&&!1!==e.xrayed&&(t|=se),this._highlighted&&!1!==e.highlighted&&(t|=re),this._selected&&!1!==e.selected&&(t|=oe),e.flags=t,this._createEntity(e)}_createEntity(e){let t=[];for(let i=0,s=e.meshIds.length;ie.sortIdt.sortId?1:0));for(let e=0,t=this.layerList.length;e0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t0){const t=`${this.id}-dummyEntityForUnusedMeshes`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}drawColorOpaque(e,t){const i=this.renderFlags;for(let t=0,s=i.visibleLayers.length;t65536?16:8)}else n=[{positionsCompressed:s,indices:r,edgeIndices:o}];return n}class Bc extends L{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;ep.has(e.id)||g.has(e.id)||f.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):p.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,n=i.originalSystemId,a={ifc_guid:n,originating_system:this.originatingSystem};return n!==o&&(a.authoring_tool_id=o),e[r].push(a),e}),{}),_=Object.entries(m).map((([e,t])=>({color:e,components:t})));o.components.coloring=_;const v=t.objectIds,b=t.visibleObjects,y=t.visibleObjectIds,B=v.filter((e=>!b[e])),w=t.selectedObjectIds;return e.defaultInvisible||y.length0&&e.clipping_planes.forEach((function(e){let t=Fc(e.location,wc),i=Fc(e.direction,wc);A&&d.negateVec3(i),d.subVec3(t,l),r.yUp&&(t=Dc(t),i=Dc(i)),new Br(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){const t=[],i=[];let r=0;e.lines.forEach((e=>{e.start_point&&e.end_point&&(t.push(e.start_point.x),t.push(e.start_point.y),t.push(e.start_point.z),t.push(e.end_point.x),t.push(e.end_point.y),t.push(e.end_point.z),i.push(r++),i.push(r++))})),new Bc(s,{positions:t,indices:i,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){const t=e.bitmap_type||"jpg",i=e.bitmap_data;let o=Fc(e.location,xc),n=Fc(e.normal,Pc),a=Fc(e.up,Cc),l=e.height||1;t&&i&&o&&n&&a&&(r.yUp&&(o=Dc(o),n=Dc(n),a=Dc(a)),new Ao(s,{src:i,type:t,pos:o,normal:n,up:a,clippable:!1,collidable:!0,height:l}))})),a&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==r.spaces_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcSpace"),!0),r.space_boundaries_visible,!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!0),r.space_boundaries_translucent,void 0!==r.openings_translucent&&s.setObjectsXRayed(i.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((e=>this._withBCFComponent(t,e,(e=>e.xrayed=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let a,A,h,c;if(e.perspective_camera?(a=Fc(e.perspective_camera.camera_view_point,wc),A=Fc(e.perspective_camera.camera_direction,wc),h=Fc(e.perspective_camera.camera_up_vector,wc),r.perspective.fov=e.perspective_camera.field_of_view,c="perspective"):(a=Fc(e.orthogonal_camera.camera_view_point,wc),A=Fc(e.orthogonal_camera.camera_direction,wc),h=Fc(e.orthogonal_camera.camera_up_vector,wc),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,c="ortho"),d.subVec3(a,l),r.yUp&&(a=Dc(a),A=Dc(A),h=Dc(h)),o){const e=s.pick({pickSurface:!0,origin:a,direction:A});A=e?e.worldPos:d.addVec3(a,A,wc)}else A=d.addVec3(a,A,wc);n?(r.eye=a,r.look=A,r.up=h,r.projection=c):i.cameraFlight.flyTo({eye:a,look:A,up:h,duration:t.duration,projection:c})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}}if(t.ifc_guid){const o=t.ifc_guid,n=r.objects[o];if(n)return void i(n);if(e.updateCompositeObjects){if(s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}Object.keys(r.models).forEach((t=>{const n=d.globalizeObjectId(t,o),a=r.objects[n];if(a)i(a);else if(e.updateCompositeObjects){s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}}))}}destroy(){super.destroy()}}function Ec(e){return{x:e[0],y:e[1],z:e[2]}}function Fc(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function Ic(e){return new Float64Array([e[0],-e[2],e[1]])}function Dc(e){return new Float64Array([e[0],e[2],-e[1]])}const Sc=d.vec3(),Tc=(e,t,i,s)=>{var r=e-i,o=t-s;return Math.sqrt(r*r+o*o)};class Lc extends L{constructor(e,t={}){if(super(e.viewer.scene,t),this.plugin=e,this._container=t.container,!this._container)throw"config missing: container";this._eventSubs={};var i=this.plugin.viewer.scene;this._originMarker=new ue(i,t.origin),this._targetMarker=new ue(i,t.target),this._originWorld=d.vec3(),this._targetWorld=d.vec3(),this._wp=new Float64Array(24),this._vp=new Float64Array(24),this._pp=new Float64Array(24),this._cp=new Float64Array(8),this._xAxisLabelCulled=!1,this._yAxisLabelCulled=!1,this._zAxisLabelCulled=!1,this._color=t.color||this.plugin.defaultColor;const s=t.onMouseOver?e=>{t.onMouseOver(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,r=t.onMouseLeave?e=>{t.onMouseLeave(e,this),this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,o=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},n=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},a=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},l=t.onContextMenu?e=>{t.onContextMenu(e,this)}:null,A=e=>{this.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};this._originDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._targetDot=new fe(this._container,{fillColor:this._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthWire=new pe(this._container,{color:this._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisWire=new pe(this._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisWire=new pe(this._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisWire=new pe(this._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._lengthLabel=new ge(this._container,{fillColor:this._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._xAxisLabel=new ge(this._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._yAxisLabel=new ge(this._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._zAxisLabel=new ge(this._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:s,onMouseLeave:r,onMouseWheel:A,onMouseDown:o,onMouseUp:n,onMouseMove:a,onContextMenu:l}),this._measurementOrientation="Horizontal",this._wpDirty=!1,this._vpDirty=!1,this._cpDirty=!1,this._sectionPlanesDirty=!0,this._visible=!1,this._originVisible=!1,this._targetVisible=!1,this._wireVisible=!1,this._axisVisible=!1,this._xAxisVisible=!1,this._yAxisVisible=!1,this._zAxisVisible=!1,this._axisEnabled=!0,this._xLabelEnabled=!1,this._yLabelEnabled=!1,this._zLabelEnabled=!1,this._lengthLabelEnabled=!1,this._labelsVisible=!1,this._labelsOnWires=!1,this._clickable=!1,this._originMarker.on("worldPos",(e=>{this._originWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._targetMarker.on("worldPos",(e=>{this._targetWorld.set(e||[0,0,0]),this._wpDirty=!0,this._needUpdate(0)})),this._onViewMatrix=i.camera.on("viewMatrix",(()=>{this._vpDirty=!0,this._needUpdate(0)})),this._onProjMatrix=i.camera.on("projMatrix",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onCanvasBoundary=i.canvas.on("boundary",(()=>{this._cpDirty=!0,this._needUpdate(0)})),this._onMetricsUnits=i.metrics.on("units",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsScale=i.metrics.on("scale",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onMetricsOrigin=i.metrics.on("origin",(()=>{this._cpDirty=!0,this._needUpdate()})),this._onSectionPlaneUpdated=i.on("sectionPlaneUpdated",(()=>{this._sectionPlanesDirty=!0,this._needUpdate()})),this.approximate=t.approximate,this.visible=t.visible,this.originVisible=t.originVisible,this.targetVisible=t.targetVisible,this.wireVisible=t.wireVisible,this.axisVisible=t.axisVisible,this.xAxisVisible=t.xAxisVisible,this.yAxisVisible=t.yAxisVisible,this.zAxisVisible=t.zAxisVisible,this.xLabelEnabled=t.xLabelEnabled,this.yLabelEnabled=t.yLabelEnabled,this.zLabelEnabled=t.zLabelEnabled,this.lengthLabelEnabled=t.lengthLabelEnabled,this.labelsVisible=t.labelsVisible,this.labelsOnWires=t.labelsOnWires,this.useRotationAdjustment=t.useRotationAdjustment}_update(){if(!this._visible)return;const e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&(d.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}const t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){d.transformPositions4(e.camera.project.matrix,this._vp,this._pp);var s=this._pp,r=this._cp,o=e.canvas.canvas.getBoundingClientRect();const t=this._container.getBoundingClientRect();var n=o.top-t.top,a=o.left-t.left,l=e.canvas.boundary,A=l[2],h=l[3],c=0;const i=this.plugin.viewer.scene.metrics,f=i.scale,g=i.units,m=i.unitsInfo[g].abbrev;for(var u=0,p=s.length;ue.offsetTop+(e.offsetParent&&e.offsetParent!==s.parentNode&&h(e.offsetParent)),c=e=>e.offsetLeft+(e.offsetParent&&e.offsetParent!==s.parentNode&&c(e.offsetParent)),u=d.vec2();this._onCameraControlHoverSnapOrSurface=i.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(e=>{const t=e.snappedCanvasPos||e.canvasPos;r=!0,o.set(e.worldPos),n.set(e.canvasPos),0===this._mouseState?(this._canvasToPagePos?(this._canvasToPagePos(s,t,u),this._markerDiv.style.left=u[0]-5+"px",this._markerDiv.style.top=u[1]-5+"px"):(this._markerDiv.style.left=c(s)+t[0]-5+"px",this._markerDiv.style.top=h(s)+t[1]-5+"px"),this._markerDiv.style.background="pink",e.snappedToVertex||e.snappedToEdge?(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos,this.pointerLens.snapped=!0),this._markerDiv.style.background="greenyellow",this._markerDiv.style.border="2px solid green"):(this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.canvasPos,this.pointerLens.snapped=!1),this._markerDiv.style.background="pink",this._markerDiv.style.border="2px solid red"),A=e.entity):(this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px"),s.style.cursor="pointer",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=this._currentDistanceMeasurementInitState.wireVisible,this._currentDistanceMeasurement.axisVisible=this._currentDistanceMeasurementInitState.axisVisible&&this.distanceMeasurementsPlugin.defaultAxisVisible,this._currentDistanceMeasurement.xAxisVisible=this._currentDistanceMeasurementInitState.xAxisVisible&&this.distanceMeasurementsPlugin.defaultXAxisVisible,this._currentDistanceMeasurement.yAxisVisible=this._currentDistanceMeasurementInitState.yAxisVisible&&this.distanceMeasurementsPlugin.defaultYAxisVisible,this._currentDistanceMeasurement.zAxisVisible=this._currentDistanceMeasurementInitState.zAxisVisible&&this.distanceMeasurementsPlugin.defaultZAxisVisible,this._currentDistanceMeasurement.targetVisible=this._currentDistanceMeasurementInitState.targetVisible,this._currentDistanceMeasurement.target.worldPos=o.slice(),this._markerDiv.style.left="-10000px",this._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=e=>{1===e.which&&(a=e.clientX,l=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=t=>{1===t.which&&(t.clientX>a+20||t.clientXl+20||t.clientY{this.pointerLens&&(this.pointerLens.visible=!0,this.pointerLens.canvasPos=e.canvasPos,this.pointerLens.snappedCanvasPos=e.snappedCanvasPos||e.canvasPos),r=!1,this._markerDiv.style.left="-100px",this._markerDiv.style.top="-100px",this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.axisVisible=!1),s.style.cursor="default"})),this._active=!0}deactivate(){if(!this._active)return;this.fire("activated",!1),this.pointerLens&&(this.pointerLens.visible=!1),this._markerDiv&&this._destroyMarkerDiv(),this.reset();const e=this.scene.canvas.canvas;e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp);const t=this.distanceMeasurementsPlugin.viewer.cameraControl;t.off(this._onCameraControlHoverSnapOrSurface),t.off(this._onCameraControlHoverSnapOrSurfaceOff),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._active=!1}reset(){this._active&&(this._destroyMarkerDiv(),this._initMarkerDiv(),this._currentDistanceMeasurement&&(this.distanceMeasurementsPlugin.fire("measurementCancel",this._currentDistanceMeasurement),this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),this._mouseState=0)}get currentMeasurement(){return this._currentDistanceMeasurement}destroy(){this.deactivate(),super.destroy()}}class kc extends z{constructor(e,t={}){super("DistanceMeasurements",e),this._pointerLens=t.pointerLens,this._container=t.container||document.body,this._defaultControl=null,this._measurements={},this.labelMinAxisLength=t.labelMinAxisLength,this.defaultVisible=!1!==t.defaultVisible,this.defaultOriginVisible=!1!==t.defaultOriginVisible,this.defaultTargetVisible=!1!==t.defaultTargetVisible,this.defaultWireVisible=!1!==t.defaultWireVisible,this.defaultXLabelEnabled=!1!==t.defaultXLabelEnabled,this.defaultYLabelEnabled=!1!==t.defaultYLabelEnabled,this.defaultZLabelEnabled=!1!==t.defaultZLabelEnabled,this.defaultLengthLabelEnabled=!1!==t.defaultLengthLabelEnabled,this.defaultLabelsVisible=!1!==t.defaultLabelsVisible,this.defaultAxisVisible=!1!==t.defaultAxisVisible,this.defaultXAxisVisible=!1!==t.defaultXAxisVisible,this.defaultYAxisVisible=!1!==t.defaultYAxisVisible,this.defaultZAxisVisible=!1!==t.defaultZAxisVisible,this.defaultColor=void 0!==t.defaultColor?t.defaultColor:"#00BBFF",this.zIndex=t.zIndex||1e4,this.defaultLabelsOnWires=!1!==t.defaultLabelsOnWires,this.useRotationAdjustment=void 0!==t.useRotationAdjustment&&!1!==t.useRotationAdjustment,this._onMouseOver=(e,t)=>{this.fire("mouseOver",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onMouseLeave=(e,t)=>{this.fire("mouseLeave",{plugin:this,distanceMeasurement:t,measurement:t,event:e})},this._onContextMenu=(e,t)=>{this.fire("contextMenu",{plugin:this,distanceMeasurement:t,measurement:t,event:e})}}getContainerElement(){return this._container}send(e,t){}get pointerLens(){return this._pointerLens}get control(){return this._defaultControl||(this._defaultControl=new Uc(this,{})),this._defaultControl}get measurements(){return this._measurements}set labelMinAxisLength(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}get labelMinAxisLength(){return this._labelMinAxisLength}set useRotationAdjustment(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}get useRotationAdjustment(){return this._useRotationAdjustment}createMeasurement(e={}){this.viewer.scene.components[e.id]&&(this.error("Viewer scene component with this ID already exists: "+e.id),delete e.id);const t=e.origin,i=e.target,s=new Lc(this,{id:e.id,plugin:this,container:this._container,origin:{entity:t.entity,worldPos:t.worldPos},target:{entity:i.entity,worldPos:i.worldPos},visible:e.visible,wireVisible:e.wireVisible,axisVisible:!1!==e.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==e.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==e.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisibld:!1!==e.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==e.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==e.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==e.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==e.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==e.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:e.originVisible,targetVisible:e.targetVisible,color:e.color,labelsOnWires:!1!==e.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(()=>{delete this._measurements[s.id]})),this.fire("measurementCreated",s),s}destroyMeasurement(e){const t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}setLabelsShown(e){for(const[t,i]of Object.entries(this.measurements))i.labelShown=e}setAxisVisible(e){for(const[t,i]of Object.entries(this.measurements))i.axisVisible=e;this.defaultAxisVisible=e}getAxisVisible(){return this.defaultAxisVisible}clear(){const e=Object.keys(this._measurements);for(var t=0,i=e.length;t{this.plugin.viewer.cameraControl.active=!1},c=()=>{this.plugin.viewer.cameraControl.active=!0},u=()=>{o&&(clearTimeout(o),o=null),this._currentDistanceMeasurement&&(this._currentDistanceMeasurement.destroy(),this._currentDistanceMeasurement=null),c(),this._touchState=0};i.addEventListener("touchstart",this._onCanvasTouchStart=i=>{const l=i.touches.length;if(1!==l)return void(o&&(clearTimeout(o),o=null));const c=i.touches[0],p=c.clientX,f=c.clientY;switch(n.set([p,f]),a.set([p,f]),this._touchState){case 0:if(1!==l&&null!==o)return void u();const i=t.pick({canvasPos:a,snapping:this._snapping,snapToEdge:this._snapping});if(i&&i.snapped)s.set(i.worldPos),this.pointerCircle.start(i.snappedCanvasPos);else{const e=t.pick({canvasPos:a,pickSurface:!0});if(!e||!e.worldPos)return;s.set(e.worldPos),this.pointerCircle.start(e.canvasPos)}o=setTimeout((()=>{1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{if(o=null,1!==l||a[0]>n[0]+r||a[0]n[1]+r||a[1]{this.pointerCircle.stop();const r=i.touches.length;if(1!==r||1!==i.changedTouches.length)return void(o&&(clearTimeout(o),o=null));const n=i.touches[0],l=n.clientX,h=n.clientY;if(n.identifier!==A)return;let c,u;switch(a.set([l,h]),this._touchState){case 2:this.pointerLens&&(this.pointerLens.canvasPos=a),c=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),c&&c.snapped?(this.pointerLens&&(this.pointerLens.snappedCanvasPos=c.snappedCanvasPos,this.pointerLens.snapped=!0),s.set(c.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=c.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:c.worldPos,entity:c.entity},target:{worldPos:c.worldPos,entity:c.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):(u=t.pick({canvasPos:a,pickSurface:!0}),u&&u.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=u.canvasPos,this.pointerLens.snapped=!1),s.set(u.worldPos),this._currentDistanceMeasurement?this._currentDistanceMeasurement.origin.worldPos=u.worldPos:(this._currentDistanceMeasurement=e.createMeasurement({id:d.createUUID(),origin:{worldPos:u.worldPos,entity:u.entity},target:{worldPos:u.worldPos,entity:u.entity}}),this._currentDistanceMeasurement.labelsVisible=!1,this._currentDistanceMeasurement.xAxisVisible=!1,this._currentDistanceMeasurement.yAxisVisible=!1,this._currentDistanceMeasurement.zAxisVisible=!1,this._currentDistanceMeasurement.wireVisible=!1,this._currentDistanceMeasurement.originVisible=!0,this._currentDistanceMeasurement.targetVisible=!1,this._currentDistanceMeasurement.clickable=!1),this.distanceMeasurementsPlugin.fire("measurementStart",this._currentDistanceMeasurement)):this.pointerLens&&(this.pointerLens.cursorPos=null,this.pointerLens.snapped=!1)),this._touchState=2;break;case 5:if(1!==r&&null!==o)return clearTimeout(o),o=null,this.pointerLens&&(this.pointerLens.visible=!1),void(this._touchState=7);this.pointerLens&&(this.pointerLens.canvasPos=a),c=t.pick({canvasPos:a,snapToVertex:this._snapping,snapToEdge:this._snapping}),c&&c.worldPos?(this.pointerLens&&(this.pointerLens.cursorPos=c.snappedCanvasPos,this.pointerLens.snapped=!0),this._currentDistanceMeasurement.target.worldPos=c.worldPos,this._currentDistanceMeasurement.target.entity=c.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0):(u=t.pick({canvasPos:a,pickSurface:!0}),u&&u.worldPos&&(this.pointerLens&&(this.pointerLens.cursorPos=u.canvasPos,this.pointerLens.snapped=!1),this._currentDistanceMeasurement.target.worldPos=u.worldPos,this._currentDistanceMeasurement.target.entity=u.entity,this._currentDistanceMeasurement.targetVisible=!0,this._currentDistanceMeasurement.wireVisible=!0,this._currentDistanceMeasurement.labelsVisible=!0)),this._touchState=5}}),{passive:!0}),i.addEventListener("touchend",this._onCanvasTouchEnd=i=>{this.pointerCircle.stop();const s=i.changedTouches.length;if(1!==s)return;const h=i.changedTouches[0],u=h.clientX,p=h.clientY;if(h.identifier===A)switch(o&&(clearTimeout(o),o=null),l.set([u,p]),this._touchState){case 1:{if(1!==s||u>n[0]+r||un[1]+r||pn[0]+r||un[1]+r||p{i=1e3*this._delayBeforeRestoreSeconds,s||(e.scene._renderer.setColorTextureEnabled(!this._hideColorTexture),e.scene._renderer.setPBREnabled(!this._hidePBR),e.scene._renderer.setSAOEnabled(!this._hideSAO),e.scene._renderer.setTransparentEnabled(!this._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!this._hideEdges),this._scaleCanvasResolution?e.scene.canvas.resolutionScale=this._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,s=!0)},o=()=>{e.scene.canvas.resolutionScale=this._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),s=!1};this._onCanvasBoundary=e.scene.canvas.on("boundary",r),this._onCameraMatrix=e.scene.camera.on("matrix",r),this._onSceneTick=e.scene.on("tick",(e=>{s&&(i-=e.deltaTime,(!this._delayBeforeRestore||i<=0)&&o())}));let n=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{n=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{n=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{n&&r()}))}get hideColorTexture(){return this._hideColorTexture}set hideColorTexture(e){this._hideColorTexture=e}get hidePBR(){return this._hidePBR}set hidePBR(e){this._hidePBR=e}get hideSAO(){return this._hideSAO}set hideSAO(e){this._hideSAO=e}get hideEdges(){return this._hideEdges}set hideEdges(e){this._hideEdges=e}get hideTransparentObjects(){return this._hideTransparentObjects}set hideTransparentObjects(e){this._hideTransparentObjects=!1!==e}get scaleCanvasResolution(){return this._scaleCanvasResolution}set scaleCanvasResolution(e){this._scaleCanvasResolution=e}get defaultScaleCanvasResolutionFactor(){return this._defaultScaleCanvasResolutionFactor}set defaultScaleCanvasResolutionFactor(e){this._defaultScaleCanvasResolutionFactor=e||1}get scaleCanvasResolutionFactor(){return this._scaleCanvasResolutionFactor}set scaleCanvasResolutionFactor(e){this._scaleCanvasResolutionFactor=e||.6}get delayBeforeRestore(){return this._delayBeforeRestore}set delayBeforeRestore(e){this._delayBeforeRestore=e}get delayBeforeRestoreSeconds(){return this._delayBeforeRestoreSeconds}set delayBeforeRestoreSeconds(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}send(e,t){}destroy(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy()}}class Qc{constructor(e={}){this.cacheBuster=!1!==e.cacheBuster}_cacheBusterURL(e){if(!this.cacheBuster)return e;const t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}getMetaModel(e,t,i){y.loadJSON(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLTF(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getGLB(e,t,i){y.loadArraybuffer(this._cacheBusterURL(e),(e=>{t(e)}),(function(e){i(e)}))}getArrayBuffer(e,t,i,s){!function(e,t,i,s){var r=()=>{};i=i||r,s=s||r;const o=/^data:(.*?)(;base64)?,(.*)$/,n=t.match(o);if(n){const e=!!n[2];var a=n[3];a=window.decodeURIComponent(a),e&&(a=window.atob(a));try{const e=new ArrayBuffer(a.length),t=new Uint8Array(e);for(var l=0;l{i(e)}),(function(e){s(e)}))}}class Vc{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=Hc(e,i);return s?t?jc(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=Hc(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=jc(r,[t]),i&&(r=jc(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const o=this._events[t];return void 0!==o&&i(o),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function Hc(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),o=this.getPoint(s),n=d.subVec3(o,r,[]);return d.normalizeVec3(n,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),o=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),o+=d.lenVec3(d.subVec3(t,r,[])),s.push(o),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,o=s.length;i=t||e*s[o-1];for(var n,a=0,l=o-1;a<=l;)if((n=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(n>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(o-1);var A=s[r];return(r+(i-A)/(s[r+1]-A))/(o-1)}}class zc extends Gc{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,o=t[0===s?s:s-1],n=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],A=d.vec3();return A[0]=d.catmullRomInterpolate(o[0],n[0],a[0],l[0],r),A[1]=d.catmullRomInterpolate(o[1],n[1],a[1],l[1],r),A[2]=d.catmullRomInterpolate(o[2],n[2],a[2],l[2],r),A}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const Wc=d.vec3();class Kc extends L{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new zc(this),this._lookCurve=new zc(this),this._upCurve=new zc(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Wc),t.look=this._lookCurve.getPoint(e,Wc),t.up=this._upCurve.getPoint(e,Wc)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,o=this._frames.length;e=1;e>1&&(e=1);const i=this.easing?$c._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,qc),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,Jc),s.look=d.subVec3(Jc,qc,Yc)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Yc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Zc)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,Jc),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,Yc),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,Zc)),this._projection2){const t="ortho"===this._projection2?$c._easeOutExpo(e,0,1,1):$c._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class eu extends L{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new $c(this),this._t=0,this.state=eu.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case eu.SCRUBBING:return;case eu.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=eu.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case eu.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=eu.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=eu.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=eu.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=eu.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=eu.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=eu.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=eu.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}eu.STOPPED=0,eu.SCRUBBING=1,eu.PLAYING=2,eu.PLAYING_TO=3;const tu=d.vec3(),iu=d.vec3();d.vec3();const su=d.vec3([0,-1,0]),ru=d.vec4([0,0,0,1]);class ou extends L{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new Xr(this),this._plane=new fr(this,{geometry:new zt(this,oo({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Jt(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 fr(this,{geometry:new zt(this,ro({size:1,divisions:10})),material:new Jt(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Sr(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]),X(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,tu);const s=-d.dotVec3(i,tu);d.normalizeVec3(i),d.mulVec3Scalar(i,s,iu),d.vec3PairToQuaternion(su,e,ru),this._node.quaternion=ru}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class nu extends Dt{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new At({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new st(i.scene.canvas.canvas,i.scene.canvas.gl,{size:[1024,1024]})),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function au(e){if(!lu(e.width)||!lu(e.height)){const t=document.createElement("canvas");t.width=Au(e.width),t.height=Au(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function lu(e){return 0==(e&e-1)}function Au(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class hu extends L{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new At({texture:new Hr({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_webglContextRestored(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let o=0;o{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class pu{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const fu=d.vec3();class gu{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?y.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,o=!i||i.xrayed,n=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,A=!i||i.pickable,h=!i||i.colorize,c=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class bu extends Gc{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var o=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(o)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class Bu extends bc{constructor(e,t={}){super(e,t)}}class wu extends L{constructor(e,t={}){super(e,t),this._skyboxMesh=new fr(this,{geometry:new zt(this,{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Jt(this,{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new Xr(this,{src:t.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:t.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),this.size=t.size,this.active=t.active}set size(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}get size(){return this._size}set active(e){this._skyboxMesh.visible=e}get active(){return this._skyboxMesh.visible}}class xu{transcode(e,t,i={}){}destroy(){}}const Pu=d.vec4(),Cu=d.vec4(),Mu=d.vec3(),Eu=d.vec3(),Fu=d.vec3(),Iu=d.vec4(),Du=d.vec4(),Su=d.vec4();class Tu{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,Mu);s=d.lenVec3(t){this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),X(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new qr(this._scene,_r({radius:s})),this._pivotSphere=new fr(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let o=t._lastBoundingClientRect;if(!o||t._canvasSizeChanged){const e=t.canvas;o=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(X(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Jt(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.worldUp);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,Lu)),i=d.cross3Vec3(t,e.worldUp,Ru);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),n=[0,0,-1,1],a=d.dotVec4(n,r)/d.dotVec4(n,o),l=ku;t.project.unproject(e,a,Ou,Nu,l);const A=d.normalizeVec3(d.subVec3(l,t.eye,Lu)),h=d.addVec3(t.eye,d.mulVec3Scalar(A,i,Ru),Uu);this.setPivotPos(h)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=d.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const n=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),a=this.getPivotPos();d.addVec3(o,a);let l=d.lookAtMat4v(o,a,i.worldUp);l=d.inverseMat4(l);const A=d.transformVec3(l,this._cameraOffset);l[12]-=A[0],l[13]-=A[1],l[14]-=A[2];const h=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],d.subVec3(i.eye,d.mulVec3Scalar(h,n),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class Vu{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new Re;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const Hu=d.vec2();class ju{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let n,a,l,A=0,h=0,c=0,u=0,p=!1;const f=d.vec3();let g=!0;const m=this._scene.canvas.canvas,_=[];function v(e=!0){m.style.cursor="move",A=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],c=s.pointerCanvasPos[0],u=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(p=!0,f.set(o.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;_[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:_[e.input.KEY_SHIFT]||i.planView?(n=!0,v()):(n=!0,v(!1));break;case 2:a=!0,v();break;case 3:l=!0,i.panRightClick&&v()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!n&&!a&&!l)return;const o=e.canvas.boundary,c=o[2],u=o[3],g=s.pointerCanvasPos[0],m=s.pointerCanvasPos[1],v=_[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&a||i.panRightClick&&l,b=document.pointerLockElement?t.movementX:g-A,y=document.pointerLockElement?t.movementY:m-h;if(v){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*b*i/u,r.panDeltaY+=1.5*y*i/u}else r.panDeltaX+=.5*t.ortho.scale*(b/u),r.panDeltaY+=.5*t.ortho.scale*(y/u)}else!n||a||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=b/c*i.dragRotationRate/2,r.rotateDeltaX+=y/u*(i.dragRotationRate/4)):(r.rotateDeltaY-=b/c*(1.5*i.dragRotationRate),r.rotateDeltaX+=y/u*(1.5*i.dragRotationRate)));A=g,h=m}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:n=!1,a=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,o=0,n=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,o+=i.scrollLeft,n+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+o-s,t[1]=e.pageY+n-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Hu);const i=Hu[0],s=Hu[1];Math.abs(i-c)<3&&Math.abs(s-u)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Hu,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const b=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),a=r._isKeyDownForAction(r.AXIS_VIEW_BACK),l=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),A=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),h=r._isKeyDownForAction(r.AXIS_VIEW_TOP),c=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(n||a||l||A||h||c))return;const u=e.aabb,p=d.getAABB3Diag(u);d.getAABB3Center(u,Gu);const f=Math.abs(p/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*p;Yu.orthoScale=g,n?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldRight,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):a?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldForward,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):l?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldRight,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):A?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldForward,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(o.worldUp)):h?(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldUp,f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,1,Wu),Ku))):c&&(Yu.eye.set(d.addVec3(Gu,d.mulVec3Scalar(o.worldUp,-f,zu),Xu)),Yu.look.set(Gu),Yu.up.set(d.normalizeVec3(d.mulVec3Scalar(o.worldForward,-1,Wu)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Gu),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Yu,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Yu),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Zu{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,A=!1;const h=this._scene.canvas.canvas,c=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||A)return;if(a.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,s.pointerCanvasPos,t,i),a.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=a.hasSubs("hover"),n=a.hasSubs("hoverEnter"),h=a.hasSubs("hoverOut"),c=a.hasSubs("hoverOff"),u=a.hasSubs("hoverSurface"),p=a.hasSubs("hoverSnapOrSurface");if(r||n||h||c||u||p)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.scheduleSnapOrPick=p,o.update(),o.pickResult){if(o.pickResult.entity){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),a.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t)}a.fire("hover",o.pickResult,!0),(o.pickResult.worldPos||o.pickResult.snappedWorldPos)&&a.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(a.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),a.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)});h.addEventListener("mousemove",u),h.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(l=!0),3===t.which&&(A=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(n.setPivotPos(t.worldPos),n.startPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),n.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(A=!1),n.getPivoting()&&n.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(n.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=a.hasSubs("picked"),A=a.hasSubs("pickedNothing"),h=a.hasSubs("pickedSurface"),u=a.hasSubs("doublePicked"),p=a.hasSubs("doublePickedSurface"),f=a.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||p||f))return(l||A||h)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=h,o.update(),o.pickResult?(a.fire("picked",o.pickResult,!0),o.pickedSurface&&a.fire("pickedSurface",o.pickResult,!0)):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=h,o.update();const e=o.pickResult,r=o.pickedSurface;this._timeout=setTimeout((()=>{e?(a.fire("picked",e,!0),r&&(a.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):a.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||u||p,o.schedulePickSurface=o.schedulePickEntity&&p,o.update(),o.pickResult){if(a.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(c(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(a.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(c(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class qu{constructor(e,t,i,s,r){this._scene=e;const o=e.input,n=[],a=e.canvas.canvas;let l=!0;this._onSceneMouseMove=o.on("mousemove",(()=>{l=!0})),this._onSceneKeyDown=o.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&s.mouseover&&(n[t]=!0,t===o.KEY_SHIFT&&(a.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(n[s]=!1,s===o.KEY_SHIFT&&(a.style.cursor=null),t.pivotController.getPivoting()&&t.pivotController.endPivot())})),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const A=t.cameraControl,h=a.deltaTime/1e3;if(!i.planView){const e=A._isKeyDownForAction(A.ROTATE_Y_POS,n),s=A._isKeyDownForAction(A.ROTATE_Y_NEG,n),o=A._isKeyDownForAction(A.ROTATE_X_POS,n),a=A._isKeyDownForAction(A.ROTATE_X_NEG,n),l=h*i.keyboardRotationRate;(e||s||o||a)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:a&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!n[o.KEY_CTRL]&&!n[o.KEY_ALT]){const e=A._isKeyDownForAction(A.DOLLY_BACKWARDS,n),o=A._isKeyDownForAction(A.DOLLY_FORWARDS,n);if(e||o){const n=h*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=n:e&&(r.dollyDelta+=n),l&&(s.followPointerDirty=!0,l=!1)}}const c=A._isKeyDownForAction(A.PAN_FORWARDS,n),u=A._isKeyDownForAction(A.PAN_BACKWARDS,n),d=A._isKeyDownForAction(A.PAN_LEFT,n),p=A._isKeyDownForAction(A.PAN_RIGHT,n),f=A._isKeyDownForAction(A.PAN_UP,n),g=A._isKeyDownForAction(A.PAN_DOWN,n),m=(n[o.KEY_ALT]?.3:1)*h*i.keyboardPanRate;(c||u||d||p||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),p?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:c&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}const $u=d.vec3();class ed{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,n=t.pickController,a=t.pivotController,l=t.panController;let A=1,h=1,c=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--A<=0&&(A=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.pickResult&&n.pickResult.worldPos?c=n.pickResult.worldPos:(h=1,c=null),s.followPointerDirty=!1),c){const t=Math.abs(d.lenVec3(d.subVec3(c,e.camera.eye,$u)));h=t/i.dollyProximityThreshold}h{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{id(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(id(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function id(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const sd=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class rd{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,n=t.pivotController,a=d.vec2(),l=d.vec2(),A=d.vec2(),h=d.vec2(),c=[],u=this._scene.canvas.canvas;let p=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(sd(r[0],a),i.followPointer&&(o.pickCursorPos=a,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(n.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&n.startPivot()&&n.showPivot()):(i.smartPivot?n.setCanvasPivotPos(s.pointerCanvasPos):n.setPivotPos(e.camera.look),!i.firstPerson&&n.startPivot()&&n.showPivot()))));c.length{n.getPivoting()&&n.endPivot()}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const n=e.canvas.boundary,a=n[2],u=n[3],g=t.touches;if(t.touches.length===p){if(1===p){sd(g[0],l),d.subVec2(l,c[0],h);const t=h[0],o=h[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(o)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const n=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*n/u*i.touchPanRate,r.panDeltaY+=o*n/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(o/u)*i.touchPanRate}else r.rotateDeltaY-=t/a*(1*i.dragRotationRate),r.rotateDeltaX+=o/u*(1.5*i.dragRotationRate)}else if(2===p){const t=g[0],n=g[1];sd(t,l),sd(n,A);const a=d.geometricMeanVec2(c[0],c[1]),h=d.geometricMeanVec2(l,A),p=d.vec2();d.subVec2(a,h,p);const f=p[0],m=p[1],_=e.camera,v=d.distVec2([t.pageX,t.pageY],[n.pageX,n.pageY]),b=(d.distVec2(c[0],c[1])-v)*i.touchDollyRate;if(r.dollyDelta=b,Math.abs(b)<1)if("perspective"===_.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(f/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=h}for(let e=0;e{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,o=e.changedTouches;if(a=Date.now(),1===r.length&&1===o.length){h=a,od(r[0],A);const o=A[0],n=A[1],l=r[0].pageX,c=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{t.cameraControl.fire("rightClick",{pagePos:[Math.round(l),Math.round(c)],canvasPos:[Math.round(o),Math.round(n)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else h=-1;for(;l.length{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,a=e.changedTouches,u=n.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===a.length&&h>-1&&t-h<150&&(c>-1&&h-c<325?(od(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("doublePicked",o.pickResult),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&p(o.pickResult)):(n.fire("doublePickedNothing"),i.doublePickFlyTo&&p()),c=-1):d.distVec2(l[0],A)<4&&(od(a[0],o.pickCursorPos),o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult?(o.pickResult.touchInput=!0,n.fire("picked",o.pickResult),o.pickedSurface&&n.fire("pickedSurface",o.pickResult)):n.fire("pickedNothing"),c=t),h=-1),l.length=r.length;for(let e=0,t=r.length;e{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new Vu(this,this._configs),pivotController:new Qu(i,this._configs),panController:new Tu(i),cameraFlight:new $c(this,{duration:.5})},this._handlers=[new td(this.scene,this._controllers,this._configs,this._states,this._updates),new rd(this.scene,this._controllers,this._configs,this._states,this._updates),new ju(this.scene,this._controllers,this._configs,this._states,this._updates),new Ju(this.scene,this._controllers,this._configs,this._states,this._updates),new Zu(this.scene,this._controllers,this._configs,this._states,this._updates),new nd(this.scene,this._controllers,this._configs,this._states,this._updates),new qu(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new ed(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",y.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e0?dd(t):null,n=i&&i.length>0?dd(i):null,a=e=>{if(!e)return;var t=!0;(n&&n[e.type]||o&&!o[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,l=i.length;r * Copyright (c) 2022 Niklas von Hertzen diff --git a/dist/xeokit-sdk.min.es5.js b/dist/xeokit-sdk.min.es5.js index 5db4fdf8a..43fd73eea 100644 --- a/dist/xeokit-sdk.min.es5.js +++ b/dist/xeokit-sdk.min.es5.js @@ -1,4 +1,4 @@ -var e,t=a().mark(XB),i=a().mark(YB),s=a().mark(oM);function r(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),i.push.apply(i,s)}return i}function n(e){for(var t=1;t=0;--r){var n=this.tryEntries[r],o=n.completion;if("root"===n.tryLoc)return s("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),l=i.call(n,"finallyLoc");if(a&&l){if(this.prev=0;--s){var r=this.tryEntries[s];if(r.tryLoc<=this.prev&&i.call(r,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),x(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var s=i.completion;if("throw"===s.type){var r=s.arg;x(i)}return r}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function l(e,t,i,s,r,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(s,r)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(s,r){var n=e.apply(t,i);function o(e){l(n,s,r,o,a,"next",e)}function a(e){l(n,s,r,o,a,"throw",e)}o(void 0)}))}}function A(e){return function(e){if(Array.isArray(e))return p(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var s=0,r=function(){};return{s:r,n:function(){return s>=e.length?{done:!0}:{done:!1,value:e[s++]}},e:function(e){throw e},f:r}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var s,r,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(s=i.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){a=!0,r=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw r}}return n}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,s=new Array(t);i0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this._id=V.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==i.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return C(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var s=0,r=i.length;s0,A=t._getNextId(),c=n.getTitle||function(){return n.title||""},h=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},p=n.getShown||function(){return!0},f=new G(A,c,h,d,p);if(f.parentMenu=r,l.items.push(f),u){var v=e(o);f.subMenu=v,v.parentItem=f}t._itemList.push(f),t._itemMap[f.id]=f},A=0,c=a.length;A'),s.push("
    "),i)for(var r=0,n=i.length;r'+d+" [MORE]"):s.push('
  • '+d+"
  • ")}}s.push("
"),s.push("");var p=s.join("");document.body.insertAdjacentHTML("beforeend",p);var f=document.querySelector("."+e.id);e.menuElement=f,f.style["border-radius"]="4px",f.style.display="none",f.style["z-index"]=3e5,f.style.background="white",f.style.border="1px solid black",f.style["box-shadow"]="0 4px 5px 0 gray",f.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var m=0,_=i.length;m<_;m++){var y=i[m].items;if(y)for(var b=function(e,i){var s=y[e],r=s.subMenu;if(s.itemElement=document.getElementById(s.id),!s.itemElement)return console.error("ContextMenu item element not found: "+s.id),"continue";s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=s.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==s.enabled){var i=s.itemElement,r=t.menuElement,n=i.getBoundingClientRect();r.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),r||(s.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),s.itemElement.addEventListener("mouseup",(function(e){3===e.which&&(e.preventDefault(),v._context&&!1!==s.enabled&&(s.doAction&&s.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus())))})),s.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==s.enabled&&s.doHover&&s.doHover(v._context)})))},w=0,B=y.length;wwindow.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),W=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.viewer=t,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=s.zoomLevel||2,this._active=!1!==s.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(function(){i._active&&i._visible&&i.update()}))}return C(e,[{key:"update",value:function(){if(this._active&&this._visible&&this._canvasPos){var e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop="".concat(t.bottom-t.top-this._lensCanvas.height-85,"px"):this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);var s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);var r=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){var n=this._snappedCanvasPos[0]-this._canvasPos[0],o=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft="".concat(r[0]+n*this._zoomLevel-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]+o*this._zoomLevel-10,"px")}else this._lensCursorDiv.style.marginLeft="".concat(r[0]-10,"px"),this._lensCursorDiv.style.marginTop="".concat(r[1]-10,"px")}}},{key:"zoomFactor",get:function(){return this._zoomFactor},set:function(e){this._zoomFactor=e,this.update()}},{key:"canvasPos",get:function(){return this._canvasPos},set:function(e){this._canvasPos=e,this.update()}},{key:"snappedCanvasPos",get:function(){return this._snappedCanvasPos},set:function(e){this._snappedCanvasPos=e,this.update()}},{key:"snapped",get:function(){return this._snapped},set:function(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}},{key:"active",get:function(){return this._active},set:function(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"destroy",value:function(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}]),e}(),K=!0,X=K?Float64Array:Float32Array,Y=new X(3),J=new X(16),Z=new X(16),q=new X(4),$={setDoublePrecisionEnabled:function(e){X=(K=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return K},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new X(e||2)},vec3:function(e){return new X(e||3)},vec4:function(e){return new X(e||4)},mat3:function(e){return new X(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new X(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},mat4:function(e){return new X(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var s=new X(2),r=0,n=e.length;r>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&s|128]).concat(e[s>>8&255],"-").concat(e[s>>16&255]).concat(e[s>>24&255]).concat(e[255&r]).concat(e[r>>8&255]).concat(e[r>>16&255]).concat(e[r>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,e))},fmod:function(e,t){if(e1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new X(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=$.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=$.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=$.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,s=(t=Array.prototype.slice.call(t)).length;i0&&void 0!==arguments[0]?arguments[0]:new X(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},identityMat3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new X(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},isIdentityMat4:function(e){return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},negateMat4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},addMat4:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return $.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],u=e[6],A=e[7],c=e[8],h=e[9],d=e[10],p=e[11],f=e[12],v=e[13],g=e[14],m=e[15],_=t[0],y=t[1],b=t[2],w=t[3],B=t[4],x=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],k=t[11],I=t[12],D=t[13],S=t[14],T=t[15];return i[0]=_*s+y*a+b*c+w*f,i[1]=_*r+y*l+b*h+w*v,i[2]=_*n+y*u+b*d+w*g,i[3]=_*o+y*A+b*p+w*m,i[4]=B*s+x*a+P*c+C*f,i[5]=B*r+x*l+P*h+C*v,i[6]=B*n+x*u+P*d+C*g,i[7]=B*o+x*A+P*p+C*m,i[8]=M*s+E*a+F*c+k*f,i[9]=M*r+E*l+F*h+k*v,i[10]=M*n+E*u+F*d+k*g,i[11]=M*o+E*A+F*p+k*m,i[12]=I*s+D*a+S*c+T*f,i[13]=I*r+D*l+S*h+T*v,i[14]=I*n+D*u+S*d+T*g,i[15]=I*o+D*A+S*p+T*m,i},mulMat3:function(e,t,i){i||(i=new X(9));var s=e[0],r=e[3],n=e[6],o=e[1],a=e[4],l=e[7],u=e[2],A=e[5],c=e[8],h=t[0],d=t[3],p=t[6],f=t[1],v=t[4],g=t[7],m=t[2],_=t[5],y=t[8];return i[0]=s*h+r*f+n*m,i[3]=s*d+r*v+n*_,i[6]=s*p+r*g+n*y,i[1]=o*h+a*f+l*m,i[4]=o*d+a*v+l*_,i[7]=o*p+a*g+l*y,i[2]=u*h+A*f+c*m,i[5]=u*d+A*v+c*_,i[8]=u*p+A*g+c*y,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=t[0],r=t[1],n=t[2],o=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*o,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*o,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*o,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],s=e[14],r=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var l=e[1],u=e[2],A=e[3],c=e[6],h=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=o,e[4]=l,e[6]=a,e[7]=n,e[8]=u,e[9]=c,e[11]=s,e[12]=A,e[13]=h,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],u=e[8],A=e[9],c=e[10],h=e[11],d=e[12],p=e[13],f=e[14],v=e[15];return d*A*a*r-u*p*a*r-d*o*c*r+n*p*c*r+u*o*f*r-n*A*f*r-d*A*s*l+u*p*s*l+d*i*c*l-t*p*c*l-u*i*f*l+t*A*f*l+d*o*s*h-n*p*s*h-d*i*a*h+t*p*a*h+n*i*f*h-t*o*f*h-u*o*s*v+n*A*s*v+u*i*a*v-t*A*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],u=e[7],A=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],v=e[14],g=e[15],m=i*a-s*o,_=i*l-r*o,y=i*u-n*o,b=s*l-r*a,w=s*u-n*a,B=r*u-n*l,x=A*f-c*p,P=A*v-h*p,C=A*g-d*p,M=c*v-h*f,E=c*g-d*f,F=h*g-d*v,k=1/(m*F-_*E+y*M+b*C-w*P+B*x);return t[0]=(a*F-l*E+u*M)*k,t[1]=(-s*F+r*E-n*M)*k,t[2]=(f*B-v*w+g*b)*k,t[3]=(-c*B+h*w-d*b)*k,t[4]=(-o*F+l*C-u*P)*k,t[5]=(i*F-r*C+n*P)*k,t[6]=(-p*B+v*y-g*_)*k,t[7]=(A*B-h*y+d*_)*k,t[8]=(o*E-a*C+u*x)*k,t[9]=(-i*E+s*C-n*x)*k,t[10]=(p*w-f*y+g*m)*k,t[11]=(-A*w+c*y-d*m)*k,t[12]=(-o*M+a*P-l*x)*k,t[13]=(i*M-s*P+r*x)*k,t[14]=(-p*b+f*_-v*m)*k,t[15]=(A*b-c*_+h*m)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||$.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||$.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(O=new X(3),function(e,t,i,s){return O[0]=e,O[1]=t,O[2]=i,$.translationMat4v(O,s)}),translationMat4s:function(e,t){return $.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return $.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,s){var r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;var n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;var o=s[11];s[8]+=o*e,s[9]+=o*t,s[10]+=o*i;var a=s[15];return s[12]+=a*e,s[13]+=a*t,s[14]+=a*i,s},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var s,r,n,o,a,l,u=$.normalizeVec4([t[0],t[1],t[2],0],[]),A=Math.sin(e),c=Math.cos(e),h=1-c,d=u[0],p=u[1],f=u[2];return s=d*p,r=p*f,n=f*d,o=d*A,a=p*A,l=f*A,(i=i||$.mat4())[0]=h*d*d+c,i[1]=h*s+l,i[2]=h*n-a,i[3]=0,i[4]=h*s-l,i[5]=h*p*p+c,i[6]=h*r+o,i[7]=0,i[8]=h*n+a,i[9]=h*r-o,i[10]=h*f*f+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,s,r){return $.rotationMat4v(e,[t,i,s],r)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new X(3);return function(t,i,s,r){return e[0]=t,e[1]=i,e[2]=s,$.scalingMat4v(e,r)}}(),scaleMat4c:function(e,t,i,s){return s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s},scaleMat4v:function(e,t){var i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:function(e){return $.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.mat4(),s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,u=n+n,A=s*a,c=s*l,h=s*u,d=r*l,p=r*u,f=n*u,v=o*a,g=o*l,m=o*u;return i[0]=1-(d+f),i[1]=c+m,i[2]=h-g,i[3]=0,i[4]=c-m,i[5]=1-(A+f),i[6]=p+v,i[7]=0,i[8]=h+g,i[9]=p-v,i[10]=1-(A+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=$.clamp,r=e[0],n=e[4],o=e[8],a=e[1],l=e[5],u=e[9],A=e[2],c=e[6],h=e[10];return"XYZ"===t?(i[1]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-u,h),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(o,h),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-A,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-A,h),i[2]=Math.atan2(-n,l)):(i[1]=0,i[2]=Math.atan2(a,r))):"ZYX"===t?(i[1]=Math.asin(-s(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(c,h),i[2]=Math.atan2(a,r)):(i[0]=0,i[2]=Math.atan2(-n,l))):"YZX"===t?(i[2]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-u,l),i[1]=Math.atan2(-A,r)):(i[0]=0,i[1]=Math.atan2(o,h))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(o,r)):(i[0]=Math.atan2(-u,h),i[1]=0)),i},composeMat4:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.mat4();return $.quaternionToRotationMat4(t,s),$.scaleMat4v(i,s),$.translateMat4v(e,s),s},decomposeMat4:function(){var e=new X(3),t=new X(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=$.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=$.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var l=$.lenVec3(e);$.determinantMat4(i)<0&&(o=-o),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);var u=1/o,A=1/a,c=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=A,t[5]*=A,t[6]*=A,t[8]*=c,t[9]*=c,t[10]*=c,$.mat4ToQuaternion(t,r),n[0]=o,n[1]=a,n[2]=l,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,s){s||(s=$.mat4());var r,n,o,a,l,u,A,c,h,d,p=e[0],f=e[1],v=e[2],g=i[0],m=i[1],_=i[2],y=t[0],b=t[1],w=t[2];return p===y&&f===b&&v===w?$.identityMat4():(r=p-y,n=f-b,o=v-w,a=m*(o*=d=1/Math.sqrt(r*r+n*n+o*o))-_*(n*=d),l=_*(r*=d)-g*o,u=g*n-m*r,(d=Math.sqrt(a*a+l*l+u*u))?(a*=d=1/d,l*=d,u*=d):(a=0,l=0,u=0),A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,(d=Math.sqrt(A*A+c*c+h*h))?(A*=d=1/d,c*=d,h*=d):(A=0,c=0,h=0),s[0]=a,s[1]=A,s[2]=r,s[3]=0,s[4]=l,s[5]=c,s[6]=n,s[7]=0,s[8]=u,s[9]=h,s[10]=o,s[11]=0,s[12]=-(a*p+l*f+u*v),s[13]=-(A*p+c*f+h*v),s[14]=-(r*p+n*f+o*v),s[15]=1,s)},lookAtMat4c:function(e,t,i,s,r,n,o,a,l){return $.lookAtMat4v([e,t,i],[s,r,n],[o,a,l],[])},orthoMat4c:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/l,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/u,o[11]=0,o[12]=-(e+t)/a,o[13]=-(s+i)/l,o[14]=-(n+r)/u,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=$.mat4());var s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];$.addVec4(r,s,J),$.subVec4(r,s,Z);var n=2*s[2],o=Z[0],a=Z[1],l=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=J[0]/o,i[9]=J[1]/a,i[10]=-J[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/l,i[15]=0,i},frustumMat4:function(e,t,i,s,r,n,o){o||(o=$.mat4());var a=t-e,l=s-i,u=n-r;return o[0]=2*r/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*r/l,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(s+i)/l,o[10]=-(n+r)/u,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*r*2/u,o[15]=0,o},perspectiveMat4:function(e,t,i,s,r){var n=[],o=[];return n[2]=i,o[2]=s,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],$.frustumMat4v(n,o,r)},compareMat4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},transformPoint3:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var s,r,n,o,a,l=i||[],u=t.length,A=e[0],c=e[1],h=e[2],d=e[3],p=e[4],f=e[5],v=e[6],g=e[7],m=e[8],_=e[9],y=e[10],b=e[11],w=e[12],B=e[13],x=e[14],P=e[15],C=0;C2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2];e[3];var c=e[4],h=e[5],d=e[6];e[7];var p=e[8],f=e[9],v=e[10];e[11];var g=e[12],m=e[13],_=e[14];for(e[15],i=0;i2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;i3&&void 0!==arguments[3]?arguments[3]:e,r=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return s[0]=o*r-a*n+t[0],s[1]=o*n+a*r+t[1],e},rotateVec3X:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z:function(e,t,i,s){var r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4:function(e,t){var i=1/e[3];return(t=t||$.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(L=new X(16),R=new X(16),U=new X(16),function(e,t,i,s){return this.transformVec3(this.mulMat4(this.inverseMat4(t,L),this.inverseMat4(i,R),U),e,s)}),lerpVec3:function(e,t,i,s,r,n){var o=n||$.vec3(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o},lerpMat4:function(e,t,i,s,r,n){var o=n||$.mat4(),a=(e-t)/(i-t);return o[0]=s[0]+a*(r[0]-s[0]),o[1]=s[1]+a*(r[1]-s[1]),o[2]=s[2]+a*(r[2]-s[2]),o[3]=s[3]+a*(r[3]-s[3]),o[4]=s[4]+a*(r[4]-s[4]),o[5]=s[5]+a*(r[5]-s[5]),o[6]=s[6]+a*(r[6]-s[6]),o[7]=s[7]+a*(r[7]-s[7]),o[8]=s[8]+a*(r[8]-s[8]),o[9]=s[9]+a*(r[9]-s[9]),o[10]=s[10]+a*(r[10]-s[10]),o[11]=s[11]+a*(r[11]-s[11]),o[12]=s[12]+a*(r[12]-s[12]),o[13]=s[13]+a*(r[13]-s[13]),o[14]=s[14]+a*(r[14]-s[14]),o[15]=s[15]+a*(r[15]-s[15]),o},flatten:function(e){var t,i,s,r,n,o=[];for(t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:$.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0]*$.DEGTORAD/2,r=e[1]*$.DEGTORAD/2,n=e[2]*$.DEGTORAD/2,o=Math.cos(s),a=Math.cos(r),l=Math.cos(n),u=Math.sin(s),A=Math.sin(r),c=Math.sin(n);return"XYZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"YXZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"ZXY"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"ZYX"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"YZX"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l-u*A*c):"XZY"===t&&(i[0]=u*a*l-o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l+u*A*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),s=e[0],r=e[4],n=e[8],o=e[1],a=e[5],l=e[9],u=e[2],A=e[6],c=e[10],h=s+a+c;return h>0?(t=.5/Math.sqrt(h+1),i[3]=.25/t,i[0]=(A-l)*t,i[1]=(n-u)*t,i[2]=(o-r)*t):s>a&&s>c?(t=2*Math.sqrt(1+s-a-c),i[3]=(A-l)/t,i[0]=.25*t,i[1]=(r+o)/t,i[2]=(n+u)/t):a>c?(t=2*Math.sqrt(1+a-s-c),i[3]=(n-u)/t,i[0]=(r+o)/t,i[1]=.25*t,i[2]=(l+A)/t):(t=2*Math.sqrt(1+c-s-a),i[3]=(o-r)/t,i[0]=(n+u)/t,i[1]=(l+A)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=Math.sqrt($.dotVec3(e,e)*$.dotVec3(t,t)),r=s+$.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):$.cross3Vec3(e,t,i),i[3]=r,$.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new X(16);return function(t,i,s){return s=s||$.vec3(),$.quaternionToRotationMat4(t,e),$.mat4ToEuler(e,i,s),s}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),s=e[0],r=e[1],n=e[2],o=e[3],a=t[0],l=t[1],u=t[2],A=t[3];return i[0]=o*a+s*A+r*u-n*l,i[1]=o*l+r*A+n*a-s*u,i[2]=o*u+n*A+s*l-r*a,i[3]=o*A-s*a-r*l-n*u,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),s=t[0],r=t[1],n=t[2],o=e[0],a=e[1],l=e[2],u=e[3],A=u*s+a*n-l*r,c=u*r+l*s-o*n,h=u*n+o*r-a*s,d=-o*s-a*r-l*n;return i[0]=A*u+d*-o+c*-l-h*-a,i[1]=c*u+d*-a+h*-o-A*-l,i[2]=h*u+d*-l+A*-a-c*-o,i},quaternionToMat4:function(e,t){t=$.identityMat4(t);var i=e[0],s=e[1],r=e[2],n=e[3],o=2*i,a=2*s,l=2*r,u=o*n,A=a*n,c=l*n,h=o*i,d=a*i,p=l*i,f=a*s,v=l*s,g=l*r;return t[0]=1-(f+g),t[1]=d+c,t[2]=p-A,t[4]=d-c,t[5]=1-(h+g),t[6]=v+u,t[8]=p+A,t[9]=v-u,t[10]=1-(h+f),t},quaternionToRotationMat4:function(e,t){var i=e[0],s=e[1],r=e[2],n=e[3],o=i+i,a=s+s,l=r+r,u=i*o,A=i*a,c=i*l,h=s*a,d=s*l,p=r*l,f=n*o,v=n*a,g=n*l;return t[0]=1-(h+p),t[4]=A-g,t[8]=c+v,t[1]=A+g,t[5]=1-(u+p),t[9]=d-f,t[2]=c-v,t[6]=d+f,t[10]=1-(u+h),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=$.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return $.normalizeQuaternion($.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=(e=$.normalizeQuaternion(e,q))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:function(e){return new X(e||6)},AABB2:function(e){return new X(e||4)},OBB3:function(e){return new X(e||32)},OBB2:function(e){return new X(e||16)},Sphere3:function(e,t,i,s){return new X([e,t,i,s])},transformOBB3:function(e,t){var i,s,r,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;ia?o:a,n[1]+=l>u?l:u,n[2]+=A>c?A:c,Math.abs($.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||$.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||$.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$.AABB3();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MAX_DOUBLE,e[3]=$.MIN_DOUBLE,e[4]=$.MIN_DOUBLE,e[5]=$.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.OBB3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t},positions3ToAABB3:function(){var e=new X(3);return function(t,i,s){i=i||$.AABB3();for(var r,n,o,a=$.MAX_DOUBLE,l=$.MAX_DOUBLE,u=$.MAX_DOUBLE,A=$.MIN_DOUBLE,c=$.MIN_DOUBLE,h=$.MIN_DOUBLE,d=0,p=t.length;dA&&(A=r),n>c&&(c=n),o>h&&(h=o);return i[0]=a,i[1]=l,i[2]=u,i[3]=A,i[4]=c,i[5]=h,i}}(),OBB3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToAABB3:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),s>A&&(A=s);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r[4]=u,r[5]=A,r},points3ToSphere3:function(){var e=new X(3);return function(t,i){i=i||$.vec4();var s,r=0,n=0,o=0,a=t.length;for(s=0;su&&(u=l);return i[3]=u,i}}(),positions3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=0;for(r=0;ru&&(u=A);return s[3]=u,s}}(),OBB3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,s){s=s||$.vec4();var r,n=0,o=0,a=0,l=i.length,u=l/4;for(r=0;rc&&(c=A);return s[3]=c,s}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(),i=0,s=0,r=0,n=0,o=e.length;nt[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]0&&void 0!==arguments[0]?arguments[0]:$.AABB2();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MIN_DOUBLE,e[3]=$.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB2(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MIN_DOUBLE,l=$.MIN_DOUBLE,u=0,A=e.length;ua&&(a=t),i>l&&(l=i);return r[0]=n,r[1]=o,r[2]=a,r[3]=l,r},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]3&&void 0!==arguments[3]?arguments[3]:e,r=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(a*i),s[2]=Math.floor(o*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:function(e,t,i,s){return 2*(1-e)*(i-t)+2*e*(s-i)},tangentQuadraticBezier3:function(e,t,i,s,r){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,i,s,r){var n=.5*(i-e),o=.5*(s-t),a=r*r;return(2*t-2*i+n+o)*(r*a)+(-3*t+3*i-2*n-o)*a+n*r+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.vec3(),r=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],u=i[2]-e[2],A=n*u-o*l,c=o*a-r*u,h=r*l-n*a,d=Math.sqrt(A*A+c*c+h*h);return 0===d?(s[0]=0,s[1]=0,s[2]=0):(s[0]=A/d,s[1]=c/d,s[2]=h/d),s},rayTriangleIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3),r=new X(3);return function(n,o,a,l,u,A){A=A||$.vec3();var c=$.subVec3(l,a,e),h=$.subVec3(u,a,t),d=$.cross3Vec3(o,h,i),p=$.dotVec3(c,d);if(p<1e-6)return null;var f=$.subVec3(n,a,s),v=$.dotVec3(f,d);if(v<0||v>p)return null;var g=$.cross3Vec3(f,c,r),m=$.dotVec3(o,g);if(m<0||v+m>p)return null;var _=$.dotVec3(h,g)/p;return A[0]=n[0]+_*o[0],A[1]=n[1]+_*o[1],A[2]=n[2]+_*o[2],A}}(),rayPlaneIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),s=new X(3);return function(r,n,o,a,l,u){u=u||$.vec3(),n=$.normalizeVec3(n,e);var A=$.subVec3(a,o,t),c=$.subVec3(l,o,i),h=$.cross3Vec3(A,c,s);$.normalizeVec3(h,h);var d=-$.dotVec3(o,h),p=-($.dotVec3(r,h)+d)/$.dotVec3(n,h);return u[0]=r[0]+p*n[0],u[1]=r[1]+p*n[1],u[2]=r[2]+p*n[2],u}}(),cartesianToBarycentric:function(){var e=new X(3),t=new X(3),i=new X(3);return function(s,r,n,o,a){var l=$.subVec3(o,r,e),u=$.subVec3(n,r,t),A=$.subVec3(s,r,i),c=$.dotVec3(l,l),h=$.dotVec3(l,u),d=$.dotVec3(l,A),p=$.dotVec3(u,u),f=$.dotVec3(u,A),v=c*p-h*h;if(0===v)return null;var g=1/v,m=(p*d-h*f)*g,_=(c*f-h*d)*g;return a[0]=1-m-_,a[1]=_,a[2]=m,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,s){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:$.vec3(),n=e[0],o=e[1],a=e[2];return r[0]=t[0]*n+i[0]*o+s[0]*a,r[1]=t[1]*n+i[1]*o+s[1]*a,r[2]=t[2]*n+i[2]*o+s[2]*a,r},mergeVertices:function(e,t,i,s){var r,n,o,a,l,u,A={},c=[],h=[],d=t?[]:null,p=i?[]:null,f=[],v=Math.pow(10,4),g=0;for(l=0,u=e.length;l>24&255,o=c>>16&255,n=c>>8&255,r=255&c,s=3*t[p],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+1],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,s=3*t[p+2],u[h++]=e[s],u[h++]=e[s+1],u[h++]=e[s+2],A[d++]=r,A[d++]=n,A[d++]=o,A[d++]=a,c++;return{positions:u,colors:A}},faceToVertexNormals:function(e,t){var i,s,r,n,o,a,l,u,A,c,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},p=d.smoothNormalsAngleThreshold||20,f={},v=[],g={},m=4,_=Math.pow(10,m);for(l=0,A=e.length;ll[3]&&(l[3]=r[h]),r[h+1]l[4]&&(l[4]=r[h+1]),r[h+2]l[5]&&(l[5]=r[h+2])}if(i.length<20||n>10)return u.triangles=i,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),u.splitDim=d;var p=(l[d]+l[d+3])/2,f=new Array(i.length),v=0,g=new Array(i.length),m=0;for(o=0,a=i.length;o2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t}};$.buildEdgeIndices=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(E=i[P.index1],F=i[P.index2],(!S&&E>65535||F>65535)&&(S=!0),k.push(E),k.push(F));return S?new Uint32Array(k):new Uint16Array(k)}}(),$.planeClipsPositions3=function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:3,r=0,n=i.length;r=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&$.containsAABB3(e.left.aabb,s))this._insertEntity(e.left,t,i+1);else if(e.right&&$.containsAABB3(e.right.aabb,s))this._insertEntity(e.right,t,i+1);else{var r=e.aabb;ee[0]=r[3]-r[0],ee[1]=r[4]-r[1],ee[2]=r[5]-r[2];var n=0;if(ee[1]>ee[n]&&(n=1),ee[2]>ee[n]&&(n=2),!e.left){var o=r.slice();if(o[n+3]=(r[n]+r[n+3])/2,e.left={aabb:o},$.containsAABB3(o,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){var a=r.slice();if(a[n]=(r[n]+r[n+3])/2,e.right={aabb:a},$.containsAABB3(a,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}}},{key:"destroy",value:function(){var e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}]),e}(),ie=function(){function e(){x(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return C(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),se={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var re=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r1&&void 0!==arguments[1]?arguments[1]:null;ce.push(e),ce.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,s=(new Date).getTime(),r=0;ce.length>0&&(i<0||s0&&ae>0){var t=1e3/ae;fe+=t,de.push(t),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}for(var i in _e.scenes)_e.scenes[i].compile();be(e),pe=e};ve=function(){ye()},ge=100,me=Date.now()+ge,function e(){var t=Date.now()-me;ve(),me+=ge,setTimeout(e,Math.max(0,ge-t))}();function be(e){var t=_e.runTasks(e+10),i=_e.getNumTasks();se.frame.tasksRun=t,se.frame.tasksScheduled=i,se.frame.tasksBudget=10}!function e(){var t=Date.now();if(ae=t-pe,pe>0&&ae>0){var i=1e3/ae;fe+=i,de.push(i),de.length>=30&&(fe-=de.shift()),se.frame.fps=Math.round(fe/de.length)}be(t),function(e){for(var t in he.time=e,_e.scenes)if(_e.scenes.hasOwnProperty(t)){var i=_e.scenes[t];he.sceneId=t,he.startTime=i.startTime,he.deltaTime=null!=he.prevTime?he.time-he.prevTime:0,i.fire("tick",he,!0)}he.prevTime=e}(t),function(){var e,t,i,s,r,n=_e.scenes,o=!1;for(r in n)n.hasOwnProperty(r)&&(e=n[r],(t=ue[r])||(t=ue[r]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),s=e.ticksPerRender,t.ticksPerRender!==s&&(t.ticksPerRender=s,t.renderCountdown=s),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=s))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(ye):requestAnimationFrame(e)}();var we=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,t&&t._own(this)}return C(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+le.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var i=e.component,s=e.sceneDefault,r=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(le.isNumeric(i)||le.isString(i))){var l=i;if(!(i=this.scene.components[l]))return void this.error("Component not found: "+le.inQuotes(l))}if(!i)if(!0===r){var u=this.scene.types[n];for(var A in u)if(u.hasOwnProperty){i=u[A];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+le.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+le.inQuotes(i.id))}this._attachments||(this._attachments={});var c,h,d,p=this._attached[t];if(p){if(i&&p.id===i.id)return;var f=this._attachments[p.id];for(h=0,d=(c=f.subs).length;h=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Me=C((function e(){x(this,e),this.planes=[new Ce,new Ce,new Ce,new Ce,new Ce,new Ce]}));function Ee(e,t,i){var s=$.mulMat4(i,t,Pe),r=s[0],n=s[1],o=s[2],a=s[3],l=s[4],u=s[5],A=s[6],c=s[7],h=s[8],d=s[9],p=s[10],f=s[11],v=s[12],g=s[13],m=s[14],_=s[15];e.planes[0].set(a-r,c-l,f-h,_-v),e.planes[1].set(a+r,c+l,f+h,_+v),e.planes[2].set(a-n,c-u,f-d,_-g),e.planes[3].set(a+n,c+u,f+d,_+g),e.planes[4].set(a-o,c-A,f-p,_-m),e.planes[5].set(a+o,c+A,f+p,_+m)}function Fe(e,t){var i=Me.INSIDE,s=Be,r=xe;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];for(var n=[s,r],o=0;o<6;++o){var a=e.planes[o];if(a.normal[0]*n[a.testVertex[0]][0]+a.normal[1]*n[a.testVertex[1]][1]+a.normal[2]*n[a.testVertex[2]][2]+a.offset<0)return Me.OUTSIDE;a.normal[0]*n[1-a.testVertex[0]][0]+a.normal[1]*n[1-a.testVertex[1]][1]+a.normal[2]*n[1-a.testVertex[2]][2]+a.offset<0&&(i=Me.INTERSECT)}return i}Me.INSIDE=0,Me.INTERSECT=1,Me.OUTSIDE=2;var ke=function(e){g(i,we);var t=_(i);function i(){var e,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(x(this,i),!s.viewer)throw"[MarqueePicker] Missing config: viewer";if(!s.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";return(e=t.call(this,s.viewer.scene,s)).viewer=s.viewer,e._objectsKdTree3=s.objectsKdTree3,e._canvasMarqueeCorner1=$.vec2(),e._canvasMarqueeCorner2=$.vec2(),e._canvasMarquee=$.AABB2(),e._marqueeFrustum=new Me,e._marqueeFrustumProjMat=$.mat4(),e._pickMode=!1,e._marqueeElement=document.createElement("div"),document.body.appendChild(e._marqueeElement),e._marqueeElement.style.position="absolute",e._marqueeElement.style["z-index"]="40000005",e._marqueeElement.style.width="8px",e._marqueeElement.style.height="8px",e._marqueeElement.style.visibility="hidden",e._marqueeElement.style.top="0px",e._marqueeElement.style.left="0px",e._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",e._marqueeElement.style.opacity=1,e._marqueeElement.style["pointer-events"]="none",e}return C(i,[{key:"setMarqueeCorner1",value:function(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarqueeCorner2",value:function(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarquee",value:function(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}},{key:"setMarqueeVisible",value:function(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}},{key:"getMarqueeVisible",value:function(){return this._marqueVisible}},{key:"setPickMode",value:function(e){if(e!==i.PICK_MODE_INSIDE&&e!==i.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===i.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}},{key:"getPickMode",value:function(){return this._pickMode}},{key:"clear",value:function(){this.fire("clear",{})}},{key:"pick",value:function(){var e=this;this._updateMarquee(),this._buildMarqueeFrustum();var t=[];return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&function s(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(n===Me.INTERSECT&&(n=Fe(e._marqueeFrustum,r.aabb)),n!==Me.OUTSIDE){if(r.entities)for(var o=r.entities,a=0,l=o.length;a3||i>3)&&c.pick()}})),document.addEventListener("mouseup",(function(e){s.getActive()&&0===e.button&&(clearTimeout(A),d&&(c.setMarqueeVisible(!1),d=!1,p=!1,f=!0,c.viewer.cameraControl.pointerEnabled=!0))}),!0),h.addEventListener("mousemove",(function(e){s.getActive()&&0===e.button&&p&&(clearTimeout(A),d&&(o=e.pageX,a=e.pageY,u=e.offsetX,c.setMarqueeVisible(!0),c.setMarqueeCorner2([o,a]),c.setPickMode(l1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.viewer=t,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==i.active,this._visible=!1,this._running=!1,this._destroyed=!1}return C(e,[{key:"start",value:function(e){var t=this;if(!this._destroyed){this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.marginLeft="".concat(this._circlePos[0]-this._circleRadius,"px"),this._circleDiv.style.marginTop="".concat(this._circlePos[1]-this._circleRadius,"px");var i,s=this._circleMaxRadius;this._running=!0,requestAnimationFrame((function e(r){if(t._running){i||(i=r);var n=r-i,o=Math.min(n/300,1),a=s+(2-s)*o;t._circleRadius=a,t._circleDiv.style.width="".concat(t._circleRadius,"px"),t._circleDiv.style.height="".concat(t._circleRadius,"px"),t._circleDiv.style.marginLeft="".concat(t._circlePos[0]-t._circleRadius/2,"px"),t._circleDiv.style.marginTop="".concat(t._circlePos[1]-t._circleRadius/2,"px"),o<1&&requestAnimationFrame(e)}})),this._circleDiv.style.visibility="visible"}}},{key:"stop",value:function(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.visibility="hidden")}},{key:"durationMs",get:function(){return this._durationMs},set:function(e){this.stop(),this._durationMs=e}},{key:"destroy",value:function(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}]),e}(),Se=function(){function e(t,i,s){x(this,e),this.id=s&&s.id?s.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return C(e,[{key:"scheduleTask",value:function(e){_e.scheduleTask(e,null)}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var s,r=this._eventSubs[e];if(r)for(var n in r)r.hasOwnProperty(n)&&(s=r[n],this._eventCallDepth++,this._eventCallDepth<300?s.callback.call(s.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var s=this._eventSubs[e];s?this._eventSubsNum[e]++:(s={},this._eventSubs[e]=s,this._eventSubsNum[e]=1);var r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),r}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),Te=$.vec3(),Le=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,$.transformVec4(s,t,i),$.setMat4Translation(s,i,n),n.slice()}}();function Re(e,t,i){var s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=s,t[1]=n,t[2]=a,i[0]=r,i[1]=o,i[2]=l}function Ue(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,r=$.getPositionsCenter(e,Te),n=Math.round(r[0]/s)*s,o=Math.round(r[1]/s)*s,a=Math.round(r[2]/s)*s;i[0]=n,i[1]=o,i[2]=a;var l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(var u=0,A=e.length;u0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],s=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(s=Math.floor(255*e)))return}else if(i===(s=255))return;for(var r=0,n=this.meshes.length;r1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._color=s.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=s.thickness||1,this._thicknessClickable=s.thicknessClickable||6,this._visible=!0,this._culled=!1;var r=this._wire,n=r.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===s.zIndex?"2000001":s.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===s.zIndex?"2000002":s.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i)})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&(tt()?(o.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,s.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),o.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):o.addEventListener("contextmenu",(function(e){console.log(e),s.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return C(e,[{key:"visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var s=this._wireClickable.style;s.width=Math.round(e)+"px",s.left=Math.round(this._x1)+"px",s.top=Math.round(this._y1)+"px",s["-webkit-transform"]="rotate("+t+"deg)",s["-moz-transform"]="rotate("+t+"deg)",s["-ms-transform"]="rotate("+t+"deg)",s["-o-transform"]="rotate("+t+"deg)",s.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,i,s){this._x1=e,this._y1=t,this._x2=i,this._y2=s,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),st=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!s.visible,this._culled=!1;var r=this._dot,n=r.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"40000005":s.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==s.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",s.onContextMenu,t.appendChild(r);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===s.zIndex?"40000007":s.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",s.onContextMenu,t.appendChild(o),o.addEventListener("click",(function(e){t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseOver&&o.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),t.dispatchEvent(new MouseEvent("mouseover",e))})),s.onMouseLeave&&o.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i)})),s.onMouseWheel&&o.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&o.addEventListener("mousedown",(function(e){s.onMouseDown(e,i)})),s.onMouseUp&&o.addEventListener("mouseup",(function(e){s.onMouseUp(e,i)})),s.onMouseMove&&o.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&(tt()?(o.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,s.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),o.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):o.addEventListener("contextmenu",(function(e){console.log(e),s.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),s.onTouchstart&&o.addEventListener("touchstart",(function(e){s.onTouchstart(e,i)})),s.onTouchmove&&o.addEventListener("touchmove",(function(e){s.onTouchmove(e,i)})),s.onTouchend&&o.addEventListener("touchend",(function(e){s.onTouchend(e,i)})),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.borderColor)}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var s=this._dotClickable.style;s.left=Math.round(e)-9+"px",s.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),rt=function(){function e(t){var i=this,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=s.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var r=this._label,n=r.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===s.zIndex?"5000005":s.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,s.onContextMenu,r.innerText="",t.appendChild(r),this.setPos(s.x||0,s.y||0),this.setFillColor(s.fillColor),this.setBorderColor(s.fillColor),this.setText(s.text),s.onMouseOver&&r.addEventListener("mouseover",(function(e){s.onMouseOver(e,i),e.preventDefault()})),s.onMouseLeave&&r.addEventListener("mouseleave",(function(e){s.onMouseLeave(e,i),e.preventDefault()})),s.onMouseWheel&&r.addEventListener("wheel",(function(e){s.onMouseWheel(e,i)})),s.onMouseDown&&r.addEventListener("mousedown",(function(e){s.onMouseDown(e,i),e.stopPropagation()})),s.onMouseUp&&r.addEventListener("mouseup",(function(e){s.onMouseUp(e,i),e.stopPropagation()})),s.onMouseMove&&r.addEventListener("mousemove",(function(e){s.onMouseMove(e,i)})),s.onContextMenu&&(tt()?(r.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,s.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),r.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):r.addEventListener("contextmenu",(function(e){console.log(e),s.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,s){var r=e+.5*(i-e),n=t+.5*(s-t),o=this._label.style;o.left=Math.round(r)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,s,r,n){var o=(e+i+r)/3,a=(t+s+n)/3,l=this._label.style;l.left=Math.round(o)-20+"px",l.top=Math.round(a)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"setPrefix",value:function(e){this._prefix!==e&&(this._prefix=e)}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),nt=$.vec3(),ot=$.vec3(),at=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._color=r.color||e.defaultColor;var n=s.plugin.viewer.scene;s._originMarker=new et(n,r.origin),s._cornerMarker=new et(n,r.corner),s._targetMarker=new et(n,r.target),s._originWorld=$.vec3(),s._cornerWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(12),s._vp=new Float64Array(12),s._pp=new Float64Array(12),s._cp=new Int16Array(6);var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},c=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};return s._originDot=new st(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._cornerDot=new st(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetDot=new st(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._originWire=new it(s._container,{color:s._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._targetWire=new it(s._container,{color:s._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._angleLabel=new rt(s._container,{fillColor:s._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._visible=!1,s._originVisible=!1,s._cornerVisible=!1,s._targetVisible=!1,s._originWireVisible=!1,s._targetWireVisible=!1,s._angleVisible=!1,s._labelsVisible=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._cornerMarker.on("worldPos",(function(e){s._cornerWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.cornerVisible=r.cornerVisible,s.targetVisible=r.targetVisible,s.originWireVisible=r.originWireVisible,s.targetWireVisible=r.targetWireVisible,s.angleVisible=r.angleVisible,s.labelsVisible=r.labelsVisible,s}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){var t=-.3,i=this._originMarker.viewPos[2],s=this._cornerMarker.viewPos[2],r=this._targetMarker.viewPos[2];if(i>t||s>t||r>t)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=a.top-l.top,A=a.left-l.left,c=e.canvas.boundary,h=c[2],d=c[3],p=0,f=0,v=n.length;f1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene))._canvasToPagePos=r.canvasToPagePos,s.pointerLens=r.pointerLens,s._active=!1,s._mouseState=0,s._currentAngleMeasurement=null,s._initMarkerDiv(),s._onMouseHoverSurface=null,s._onHoverNothing=null,s._onPickedNothing=null,s._onPickedSurface=null,s._onInputMouseDown=null,s._onInputMouseUp=null,s._snapping=!1!==r.snapping,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this.markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this.markerDiv||this._initMarkerDiv(),this.angleMeasurementsPlugin;var t=this.scene;t.input;var i=t.canvas.canvas,s=this.angleMeasurementsPlugin.viewer.cameraControl,r=this.pointerLens,n=!1,o=null,a=0,l=0,u=$.vec3(),A=$.vec2();this._currentAngleMeasurement=null;var c=function e(t){return t.offsetTop+(t.offsetParent&&t.offsetParent!==i.parentNode&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&t.offsetParent!==i.parentNode&&e(t.offsetParent))},d=$.vec2();this._onMouseHoverSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){t.snappedToVertex||t.snappedToEdge?(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,r.snapped=!0),e.markerDiv.style.background="greenyellow",e.markerDiv.style.border="2px solid green"):(r&&(r.visible=!0,r.canvasPos=t.canvasPos,r.snappedCanvasPos=t.canvasPos,r.snapped=!1),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red");var s=t.snappedCanvasPos||t.canvasPos;switch(n=!0,o=t.entity,u.set(t.worldPos),A.set(s),e._mouseState){case 0:e._canvasToPagePos?(e._canvasToPagePos(i,s,d),e.markerDiv.style.left="".concat(d[0]-5,"px"),e.markerDiv.style.top="".concat(d[1]-5,"px")):(e.markerDiv.style.left="".concat(h(i)+s[0]-5,"px"),e.markerDiv.style.top="".concat(c(i)+s[1]-5,"px"));break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos,e._currentAngleMeasurement.corner.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos,e._currentAngleMeasurement.target.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer"}})),i.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=function(t){if(1===t.which&&!(t.clientX>a+20||t.clientXl+20||t.clientY1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"AngleMeasurements",e))._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),angleMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new ut(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.corner,r=t.target,n=new at(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:s.entity,worldPos:s.worldPos},target:{entity:r.entity,worldPos:r.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),n.clickable=!0,this.fire("measurementCreated",n),n}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s.pointerCircle=new De(e.viewer),s._active=!1;var n=document.createElement("div"),o=s.scene.canvas.canvas;return o.parentNode.insertBefore(n,o),n.style.background="black",n.style.border="2px solid blue",n.style.borderRadius="10px",n.style.width="5px",n.style.height="5px",n.style.margin="-200px -200px",n.style.zIndex="100",n.style.position="absolute",n.style.pointerEvents="none",s.markerDiv=n,s._currentAngleMeasurement=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s._longTouchTimeoutMs=300,s._snapping=!1!==r.snapping,s._touchState=0,s._attachPlugin(e,r),s}return C(i,[{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){var t=this.plugin,i=this.scene,s=i.canvas.canvas;t.pointerLens;var r=$.vec3(),n=20,o=null;this._touchState=0;var a=$.vec2(),l=$.vec2(),u=$.vec2(),A=null,c=function(){e.plugin.viewer.cameraControl.active=!1},h=function(){e.plugin.viewer.cameraControl.active=!0};s.addEventListener("touchstart",this._onCanvasTouchStart=function(s){var u=s.touches.length;if(1===u){var d=s.touches[0],p=d.clientX,f=d.clientY;switch(a.set([p,f]),l.set([p,f]),e._touchState){case 0:if(1!==u&&null!==o)return o&&(clearTimeout(o),o=null),e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null),h(),void(e._touchState=0);var v=i.pick({canvasPos:l,snapToVertex:e._snapping,snapToEdge:e._snapping});if(v&&v.snapped)r.set(v.worldPos),e.pointerCircle.start(v.snappedCanvasPos);else{var g=i.pick({canvasPos:l,pickSurface:!0});if(!g||!g.worldPos)return;r.set(g.worldPos),e.pointerCircle.start(g.canvasPos)}o=setTimeout((function(){1!==u||l[0]>a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||da[1]+n||pa[0]+n||da[1]+n||pa[0]+n||da[1]+n||p

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

";le.isArray(s)&&(s=s.join("")),s=this._renderTemplate(s.trim());var r=document.createRange().createContextualFragment(s);this._label=r.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],s=this.canvasPos;this._marker.style.left=Math.floor(t+s[0])-12+"px",this._marker.style.top=Math.floor(i+s[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+s[0]+20)+"px",this._label.style.top=Math.floor(i+s[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var i=e[t];this.setField(t,i)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),dt=$.vec3(),pt=$.vec3(),ft=$.vec3(),vt=function(e){g(i,Se);var t=_(i);function i(e,s){var r;return x(this,i),(r=t.call(this,"Annotations",e))._labelHTML=s.labelHTML||"
",r._markerHTML=s.markerHTML||"
",r._container=s.container||document.body,r._values=s.values||{},r.annotations={},r.surfaceOffset=s.surfaceOffset,r}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,i,s=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var r=e.pickResult;if(r.worldPos&&r.worldNormal){var n=$.normalizeVec3(r.worldNormal,dt),o=$.mulVec3Scalar(n,this._surfaceOffset,pt);t=$.addVec3(r.worldPos,o,ft),i=r.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ht(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:le.apply(e.values,le.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete s.annotations[u.id],s.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._canvas=r.canvas,s._element=null,s._isCustom=!1,r.elementId&&(s._element=document.getElementById(r.elementId),s._element?s._adjustPosition():s.error("Can't find given Spinner HTML element: '"+r.elementId+"' - will automatically create default element")),s._element||s._createDefaultSpinner(),s.processes=0,s}return C(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),mt=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],_t=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r))._backgroundColor=$.vec3([r.backgroundColor?r.backgroundColor[0]:1,r.backgroundColor?r.backgroundColor[1]:1,r.backgroundColor?r.backgroundColor[2]:1]),s._backgroundColorFromAmbientLight=!!r.backgroundColorFromAmbientLight,s.canvas=r.canvas,s.gl=null,s.webgl2=!1,s.transparent=!!r.transparent,s.contextAttr=r.contextAttr||{},s.contextAttr.alpha=s.transparent,s.contextAttr.preserveDrawingBuffer=!!s.contextAttr.preserveDrawingBuffer,s.contextAttr.stencil=!1,s.contextAttr.premultipliedAlpha=!!s.contextAttr.premultipliedAlpha,s.contextAttr.antialias=!1!==s.contextAttr.antialias,s.resolutionScale=r.resolutionScale,s.canvas.width=Math.round(s.canvas.clientWidth*s._resolutionScale),s.canvas.height=Math.round(s.canvas.clientHeight*s._resolutionScale),s.boundary=[s.canvas.offsetLeft,s.canvas.offsetTop,s.canvas.clientWidth,s.canvas.clientHeight],s._initWebGL(r);var n=b(s);s.canvas.addEventListener("webglcontextlost",s._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),s.canvas.addEventListener("webglcontextrestored",s._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(s.canvas),s._tick=s.scene.on("tick",(function(){o&&(o=!1,n.canvas.width=Math.round(n.canvas.clientWidth*n._resolutionScale),n.canvas.height=Math.round(n.canvas.clientHeight*n._resolutionScale),n.boundary[0]=n.canvas.offsetLeft,n.boundary[1]=n.canvas.offsetTop,n.boundary[2]=n.canvas.clientWidth,n.boundary[3]=n.canvas.clientHeight,n.fire("boundary",n.boundary))})),s._spinner=new gt(s.scene,{canvas:s.canvas,elementId:r.spinnerElementId}),s}return C(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+$.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e0?bt.FS_MAX_FLOAT_PRECISION="highp":Bt.getShaderPrecisionFormat(Bt.FRAGMENT_SHADER,Bt.MEDIUM_FLOAT).precision>0?bt.FS_MAX_FLOAT_PRECISION="mediump":bt.FS_MAX_FLOAT_PRECISION="lowp":bt.FS_MAX_FLOAT_PRECISION="mediump",bt.DEPTH_BUFFER_BITS=Bt.getParameter(Bt.DEPTH_BITS),bt.MAX_TEXTURE_SIZE=Bt.getParameter(Bt.MAX_TEXTURE_SIZE),bt.MAX_CUBE_MAP_SIZE=Bt.getParameter(Bt.MAX_CUBE_MAP_TEXTURE_SIZE),bt.MAX_RENDERBUFFER_SIZE=Bt.getParameter(Bt.MAX_RENDERBUFFER_SIZE),bt.MAX_TEXTURE_UNITS=Bt.getParameter(Bt.MAX_COMBINED_TEXTURE_IMAGE_UNITS),bt.MAX_TEXTURE_IMAGE_UNITS=Bt.getParameter(Bt.MAX_TEXTURE_IMAGE_UNITS),bt.MAX_VERTEX_ATTRIBS=Bt.getParameter(Bt.MAX_VERTEX_ATTRIBS),bt.MAX_VERTEX_UNIFORM_VECTORS=Bt.getParameter(Bt.MAX_VERTEX_UNIFORM_VECTORS),bt.MAX_FRAGMENT_UNIFORM_VECTORS=Bt.getParameter(Bt.MAX_FRAGMENT_UNIFORM_VECTORS),bt.MAX_VARYING_VECTORS=Bt.getParameter(Bt.MAX_VARYING_VECTORS),Bt.getSupportedExtensions().forEach((function(e){bt.SUPPORTED_EXTENSIONS[e]=!0})))}var xt=function(){function e(){x(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return C(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"snapped",get:function(){return this.snappedToEdge||this.snappedToVertex}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),Pt=function(){function e(t,i,s){if(x(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,s),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var r=s.split("\n"),n=[],o=0;o0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),s.push(t);return s.join("\n")}function kt(e){console.error(e.join("\n"))}var It=function(){function e(t,i){x(this,e),this.id=Et.addItem({}),this.source=i,this.init(t)}return C(e,[{key:"init",value:function(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Pt(e,e.VERTEX_SHADER,Ft(this.source.vertex)),this._fragmentShader=new Pt(e,e.FRAGMENT_SHADER,Ft(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void kt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void kt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void kt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void kt(this.errors);var t,i,s,r,n;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void kt(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}},{key:"setData",value:function(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),St=function(){function e(t,i){x(this,e),this.scene=t,this.aabb=$.AABB3(),this.origin=$.vec3(i),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return C(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],A=l[1];u+10<0||A+10<0||u-10>s||A-10>r?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=u,this.pixels[n++]=A):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("#version 300 es"),s.push("// OcclusionTester fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;");for(var r=0;r 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new It(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=i.sectionPlanes.length;r0)for(var h=s.sectionPlanes,d=0;d= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Dt(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new Dt(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new Dt(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Nt=new Float32Array(zt(17,[0,1])),Qt=new Float32Array(zt(17,[1,0])),Vt=new Float32Array(function(e,t){for(var i=[],s=0;s<=e;s++)i.push(Gt(s,t));return i}(17,4)),Ht=new Float32Array(2),jt=function(){function e(t){x(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return C(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new It(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Dt(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Dt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Dt(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var s=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;s._scene.camera.on("projMatrix",(function(){e=!0}));var t=$.mat4();return function(){return e&&$.inverseMat4(o.camera.projMatrix,t),t}}());var r=this._scene.canvas.gl,n=this._program,o=this._scene,a=r.drawingBufferWidth,l=r.drawingBufferHeight,u=o.camera.project._state,A=u.near,c=u.far;r.viewport(0,0,a,l),r.clearColor(0,0,0,1),r.enable(r.DEPTH_TEST),r.disable(r.BLEND),r.frontFace(r.CCW),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),n.bind(),Ht[0]=a,Ht[1]=l,r.uniform2fv(this._uViewport,Ht),r.uniform1f(this._uCameraNear,A),r.uniform1f(this._uCameraFar,c),r.uniform1f(this._uDepthCutoff,.01),0===i?r.uniform2fv(this._uSampleOffsets,Qt):r.uniform2fv(this._uSampleOffsets,Nt),r.uniform1fv(this._uSampleWeights,Vt);var h=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,h,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),r.drawElements(r.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Gt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function zt(e,t){for(var i=[],s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}var Wt=function(){function e(t,i,s){x(this,e),s=s||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=s.size,this._hasDepthTexture=!!s.depthTexture}return C(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=this.gl,r=s.createTexture();return s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),r}},{key:"_touch",value:function(){var e,t,i=this,s=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=s.drawingBufferWidth,t=s.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return s.deleteTexture(e)})),s.deleteFramebuffer(this.buffer.framebuf),s.deleteRenderbuffer(this.buffer.renderbuf)}for(var r,n=[],o=arguments.length,a=new Array(o),l=0;l0?n.push.apply(n,A(a.map((function(s){return i.createTexture(e,t,s)})))):n.push(this.createTexture(e,t)),this._hasDepthTexture&&(r=s.createTexture(),s.bindTexture(s.TEXTURE_2D,r),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,e,t,0,s.DEPTH_COMPONENT,s.FLOAT,null));var u=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,u),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,e,t);var c=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,c);for(var h=0;h0&&s.drawBuffers(n.map((function(e,t){return s.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,r,0):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,u),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,c),!s.isFramebuffer(c))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);var d=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(d){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+d}this.buffer={framebuf:c,renderbuf:u,texture:n[0],textures:n,depthTexture:r,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new r(n),A=this.gl;return A.readBuffer(A.COLOR_ATTACHMENT0+o),A.readPixels(a,l,1,1,i||A.RGBA,s||A.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=new i(this.buffer.width*this.buffer.height*s),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+r),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,n,0),n}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,s=t.canvas,r=t.imageData,n=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,A=new Uint8Array(4*o),c=0;c0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,s=this.buffer.height,r=this._imageDataCache;if(r&&(r.width===i&&r.height===s||(this._imageDataCache=null,r=null)),!r){var n=document.createElement("canvas"),o=n.getContext("2d");n.width=i,n.height=s,r={pixelData:new e(i*s*t),canvas:n,context:o,imageData:o.createImageData(i,s),width:i,height:s},this._imageDataCache=r}return r.context.resetTransform(),r}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Kt=function(){function e(t){x(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return C(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,s=i[e];return s||(s=new Wt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=s),s}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function Xt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Yt=function(e,t){t=t||{};var i=new yt(e),s=e.canvas.canvas,r=e.canvas.gl,n=!!t.transparent,o=t.alphaDepthMask,a=new Q({}),l={},u={},A=!0,c=!0,h=!0,d=!0,p=!0,f=!0,v=!0,g=!0,m=new Kt(e),_=!1,y=new Ot(e),b=new jt(e);function w(){A&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,s=t.drawableListPreCull,r=0;for(var n in i)i.hasOwnProperty(n)&&(s[r++]=i[n]);s.length=r}}(),A=!1,c=!0),c&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),c=!1,h=!0),h&&function(){for(var e in l)if(l.hasOwnProperty(e)){for(var t=l[e],i=t.drawableListPreCull,s=t.drawableList,r=0,n=0,o=i.length;n0)for(i.withSAO=!0,I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||G>0||N>0||Q>0){if(r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):(r.blendEquation(r.FUNC_ADD),r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||r.depthMask(!1),(N>0||Q>0)&&r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),Q>0)for(I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||W>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),W>0)for(I=0;I0)for(I=0;I0||X>0||z>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),r.enable(r.CULL_FACE),X>0)for(I=0;I0)for(I=0;I0||J>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),J>0)for(I=0;I0)for(I=0;I0||q>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&r.clear(r.DEPTH_BUFFER_BIT),r.enable(r.CULL_FACE),r.enable(r.BLEND),n?(r.blendEquation(r.FUNC_ADD),r.blendFuncSeparate(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA,r.ONE,r.ONE_MINUS_SRC_ALPHA)):r.blendFunc(r.SRC_ALPHA,r.ONE_MINUS_SRC_ALPHA),q>0)for(I=0;I0)for(I=0;I1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),w();var f=null,v=null;for(var g in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix):(A.set(h.origin||[0,0,0]),c.set(h.direction||[0,0,1]),d=$.addVec3(A,c,t),r[0]=Math.random(),r[1]=Math.random(),r[2]=Math.random(),$.normalizeVec3(r),$.cross3Vec3(c,r,n),f=$.lookAtMat4v(A,d,n,i),v=e.camera.ortho.matrix,p.origin=A,p.direction=c),u[0]=.5*s.clientWidth,u[1]=.5*s.clientHeight),l)if(l.hasOwnProperty(g))for(var _=l[g].drawableList,y=0,b=_.length;y4&&void 0!==arguments[4]?arguments[4]:C;if(!n&&!o)return this.pick({canvasPos:t,pickSurface:!0});var A=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far,s=s||30;var c=m.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*s+1,2*s+1]});i.snapVectorA=[k(t[0]*A,r.drawingBufferWidth),I(t[1]*A,r.drawingBufferHeight)],i.snapInvVectorAB=[r.drawingBufferWidth/(2*s),r.drawingBufferHeight/(2*s)],c.bind(r.RGBA32I,r.RGBA32I,r.RGBA8UI),r.viewport(0,0,c.size[0],c.size[1]),r.enable(r.DEPTH_TEST),r.frontFace(r.CCW),r.disable(r.CULL_FACE),r.depthMask(!0),r.disable(r.BLEND),r.depthFunc(r.LEQUAL),r.clear(r.DEPTH_BUFFER_BIT),r.clearBufferiv(r.COLOR,0,new Int32Array([0,0,0,0])),r.clearBufferiv(r.COLOR,1,new Int32Array([0,0,0,0])),r.clearBufferuiv(r.COLOR,2,new Uint32Array([0,0,0,0]));var h=e.camera.viewMatrix,d=e.camera.projMatrix;for(var p in l)if(l.hasOwnProperty(p))for(var f=l[p].drawableList,v=0,g=f.length;v0){var j=Math.floor(H/4),G=c.size[0],z=j%G-Math.floor(G/2),W=Math.floor(j/G)-Math.floor(G/2),K=Math.sqrt(Math.pow(z,2)+Math.pow(W,2));V.push({x:z,y:W,dist:K,isVertex:n&&o?w[H+3]>b.length/2:n,result:[w[H+0],w[H+1],w[H+2],w[H+3]],normal:[B[H+0],B[H+1],B[H+2],B[H+3]],id:[x[H+0],x[H+1],x[H+2],x[H+3]]})}var X=null,Y=null,J=null,Z=null;if(V.length>0){V.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),Z=V[0].isVertex?"vertex":"edge";var q=V[0].result,ee=V[0].normal,te=V[0].id,ie=b[q[3]],se=ie.origin,re=ie.coordinateScale;Y=$.normalizeVec3([ee[0]/$.MAX_INT,ee[1]/$.MAX_INT,ee[2]/$.MAX_INT]),X=[q[0]*re[0]+se[0],q[1]*re[1]+se[1],q[2]*re[2]+se[2]],J=a.items[te[0]+(te[1]<<8)+(te[2]<<16)+(te[3]<<24)]}if(null===P&&null==X)return null;var ne=null;null!==X&&(ne=e.camera.projectWorldPos(X));var oe=J&&J.delegatePickedEntity?J.delegatePickedEntity():J;return u.reset(),u.snappedToEdge="edge"===Z,u.snappedToVertex="vertex"===Z,u.worldPos=X,u.worldNormal=Y,u.entity=oe,u.canvasPos=t,u.snappedCanvasPos=ne||t,u}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new Rt(e,m),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in w(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.clearColor(0,0,0,0),r.enable(r.DEPTH_TEST),r.disable(r.CULL_FACE),r.disable(r.BLEND),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,s=0,n=t.length;s0&&void 0!==arguments[0]?arguments[0]:{},t=m.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),_=!0},this.renderSnapshot=function(){_&&(m.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),h=!0)},this.readSnapshot=function(e){return m.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return m.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){_&&(m.getRenderBuffer("snapshot").unbind(),_=!1)},this.destroy=function(){l={},u={},m.destroy(),y.destroy(),b.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Jt=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).KEY_BACKSPACE=8,s.KEY_TAB=9,s.KEY_ENTER=13,s.KEY_SHIFT=16,s.KEY_CTRL=17,s.KEY_ALT=18,s.KEY_PAUSE_BREAK=19,s.KEY_CAPS_LOCK=20,s.KEY_ESCAPE=27,s.KEY_PAGE_UP=33,s.KEY_PAGE_DOWN=34,s.KEY_END=35,s.KEY_HOME=36,s.KEY_LEFT_ARROW=37,s.KEY_UP_ARROW=38,s.KEY_RIGHT_ARROW=39,s.KEY_DOWN_ARROW=40,s.KEY_INSERT=45,s.KEY_DELETE=46,s.KEY_NUM_0=48,s.KEY_NUM_1=49,s.KEY_NUM_2=50,s.KEY_NUM_3=51,s.KEY_NUM_4=52,s.KEY_NUM_5=53,s.KEY_NUM_6=54,s.KEY_NUM_7=55,s.KEY_NUM_8=56,s.KEY_NUM_9=57,s.KEY_A=65,s.KEY_B=66,s.KEY_C=67,s.KEY_D=68,s.KEY_E=69,s.KEY_F=70,s.KEY_G=71,s.KEY_H=72,s.KEY_I=73,s.KEY_J=74,s.KEY_K=75,s.KEY_L=76,s.KEY_M=77,s.KEY_N=78,s.KEY_O=79,s.KEY_P=80,s.KEY_Q=81,s.KEY_R=82,s.KEY_S=83,s.KEY_T=84,s.KEY_U=85,s.KEY_V=86,s.KEY_W=87,s.KEY_X=88,s.KEY_Y=89,s.KEY_Z=90,s.KEY_LEFT_WINDOW=91,s.KEY_RIGHT_WINDOW=92,s.KEY_SELECT_KEY=93,s.KEY_NUMPAD_0=96,s.KEY_NUMPAD_1=97,s.KEY_NUMPAD_2=98,s.KEY_NUMPAD_3=99,s.KEY_NUMPAD_4=100,s.KEY_NUMPAD_5=101,s.KEY_NUMPAD_6=102,s.KEY_NUMPAD_7=103,s.KEY_NUMPAD_8=104,s.KEY_NUMPAD_9=105,s.KEY_MULTIPLY=106,s.KEY_ADD=107,s.KEY_SUBTRACT=109,s.KEY_DECIMAL_POINT=110,s.KEY_DIVIDE=111,s.KEY_F1=112,s.KEY_F2=113,s.KEY_F3=114,s.KEY_F4=115,s.KEY_F5=116,s.KEY_F6=117,s.KEY_F7=118,s.KEY_F8=119,s.KEY_F9=120,s.KEY_F10=121,s.KEY_F11=122,s.KEY_F12=123,s.KEY_NUM_LOCK=144,s.KEY_SCROLL_LOCK=145,s.KEY_SEMI_COLON=186,s.KEY_EQUAL_SIGN=187,s.KEY_COMMA=188,s.KEY_DASH=189,s.KEY_PERIOD=190,s.KEY_FORWARD_SLASH=191,s.KEY_GRAVE_ACCENT=192,s.KEY_OPEN_BRACKET=219,s.KEY_BACK_SLASH=220,s.KEY_CLOSE_BRACKET=221,s.KEY_SINGLE_QUOTE=222,s.KEY_SPACE=32,s.element=r.element,s.altDown=!1,s.ctrlDown=!1,s.mouseDownLeft=!1,s.mouseDownMiddle=!1,s.mouseDownRight=!1,s.keyDown=[],s.enabled=!0,s.keyboardEnabled=!0,s.mouseover=!1,s.mouseCanvasPos=$.vec2(),s._keyboardEventsElement=r.keyboardEventsElement||document,s._bindEvents(),s}return C(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("contextmenu",e.mouseCanvasPos,!0))});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,s){if(e.enabled){var r=Math.max(-1,Math.min(1,40*-t.deltaY));i(r)}},{passive:!0});var s,r;this.on("mousedown",(function(e){s=e[0],r=e[1]})),this.on("mouseup",(function(t){s>=t[0]-2&&s<=t[0]+2&&r>=t[1]-2&&r<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this.element.addEventListener("touchstart",this._touchstartListener=function(t){e.enabled&&A(t.changedTouches).forEach((function(t){e.fire("touchstart",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=function(t){e.enabled&&A(t.changedTouches).forEach((function(t){e.fire("touchend",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getTouchCanvasPos",value:function(e){for(var t=e.target,i=0,s=0;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,i=0,s=0;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Zt=new Q({}),qt=function(){function e(t){for(var i in x(this,e),this.id=Zt.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return C(e,[{key:"destroy",value:function(){Zt.removeItem(this.id)}}]),e}(),$t=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({boundary:[0,0,100,100]}),s.boundary=r.boundary,s.autoBoundary=r.autoBoundary,s}return C(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),ei=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).camera=e,s._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s._fov=60,s._canvasResized=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s.fov=r.fov,s.fovAxis=r.fovAxis,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),$.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),ti=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).camera=e,s._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.scale=r.scale,s.near=r.near,s.far=r.far,s._onCanvasBoundary=s.scene.canvas.on("boundary",s._needUpdate,b(s)),s}return C(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,s,r=this.scene,n=.5*this._scale,o=r.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-n,t=n,i=n/u,s=-n/u):(e=-n*u,t=n*u,i=n,s=-n),$.orthoMat4c(e,t,s,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),ii=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).camera=e,s._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),s._left=-1,s._right=1,s._bottom=-1,s._top=1,s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!0,s.left=r.left,s.right=r.right,s.bottom=r.bottom,s.top=r.top,s.near=r.near,s.far=r.far,s}return C(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){$.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),si=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).camera=e,s._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4()}),s._inverseMatrixDirty=!0,s._transposedMatrixDirty=!1,s.matrix=r.matrix,s}return C(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,s,r){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),ri=$.vec3(),ni=$.vec3(),oi=$.vec3(),ai=$.vec3(),li=$.vec3(),ui=$.vec3(),Ai=$.vec4(),ci=$.vec4(),hi=$.vec4(),di=$.mat4(),pi=$.mat4(),fi=$.vec3(),vi=$.vec3(),gi=$.vec3(),mi=$.vec3(),_i=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({deviceMatrix:$.mat4(),hasDeviceMatrix:!1,matrix:$.mat4(),normalMatrix:$.mat4(),inverseMatrix:$.mat4()}),s._perspective=new ei(b(s)),s._ortho=new ti(b(s)),s._frustum=new ii(b(s)),s._customProjection=new si(b(s)),s._project=s._perspective,s._eye=$.vec3([0,0,10]),s._look=$.vec3([0,0,0]),s._up=$.vec3([0,1,0]),s._worldUp=$.vec3([0,1,0]),s._worldRight=$.vec3([1,0,0]),s._worldForward=$.vec3([0,0,-1]),s.deviceMatrix=r.deviceMatrix,s.eye=r.eye,s.look=r.look,s.up=r.up,s.worldAxis=r.worldAxis,s.gimbalLock=r.gimbalLock,s.constrainPitch=r.constrainPitch,s.projection=r.projection,s._perspective.on("matrix",(function(){"perspective"===s._projectionType&&s.fire("projMatrix",s._perspective.matrix)})),s._ortho.on("matrix",(function(){"ortho"===s._projectionType&&s.fire("projMatrix",s._ortho.matrix)})),s._frustum.on("matrix",(function(){"frustum"===s._projectionType&&s.fire("projMatrix",s._frustum.matrix)})),s._customProjection.on("matrix",(function(){"customProjection"===s._projectionType&&s.fire("projMatrix",s._customProjection.matrix)})),s}return C(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?($.subVec3(this._eye,this._look,fi),$.normalizeVec3(fi,vi),$.mulVec3Scalar(vi,1e3,gi),$.addVec3(this._look,gi,mi),e=mi):e=this._eye,t.hasDeviceMatrix?($.lookAtMat4v(e,this._look,this._up,pi),$.mulMat4(t.deviceMatrix,pi,t.matrix)):$.lookAtMat4v(e,this._look,this._up,t.matrix),$.inverseMat4(this._state.matrix,this._state.inverseMatrix),$.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=$.subVec3(this._eye,this._look,ri);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,di),t=$.transformPoint3(di,t,ni),this.eye=$.addVec3(this._look,t,oi),this.up=$.transformPoint3(di,this._up,ai)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._eye,this._look,ri),i=$.cross3Vec3($.normalizeVec3(t,ni),$.normalizeVec3(this._up,oi));$.rotationMat4v(.0174532925*e,i,di),t=$.transformPoint3(di,t,ai),this.up=$.transformPoint3(di,this._up,li),this.eye=$.addVec3(t,this._look,ui)}}},{key:"yaw",value:function(e){var t=$.subVec3(this._look,this._eye,ri);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,di),t=$.transformPoint3(di,t,ni),this.look=$.addVec3(t,this._eye,oi),this._gimbalLock&&(this.up=$.transformPoint3(di,this._up,ai))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._look,this._eye,ri),i=$.cross3Vec3($.normalizeVec3(t,ni),$.normalizeVec3(this._up,oi));$.rotationMat4v(.0174532925*e,i,di),this.up=$.transformPoint3(di,this._up,ui),t=$.transformPoint3(di,t,ai),this.look=$.addVec3(t,this._eye,li)}}},{key:"pan",value:function(e){var t,i=$.subVec3(this._eye,this._look,ri),s=[0,0,0];if(0!==e[0]){var r=$.cross3Vec3($.normalizeVec3(i,[]),$.normalizeVec3(this._up,ni));t=$.mulVec3Scalar(r,e[0]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]}0!==e[1]&&(t=$.mulVec3Scalar($.normalizeVec3(this._up,oi),e[1]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),0!==e[2]&&(t=$.mulVec3Scalar($.normalizeVec3(i,ai),e[2]),s[0]+=t[0],s[1]+=t[1],s[2]+=t[2]),this.eye=$.addVec3(this._eye,s,li),this.look=$.addVec3(this._look,s,ui)}},{key:"zoom",value:function(e){var t=$.subVec3(this._eye,this._look,ri),i=Math.abs($.lenVec3(t,ni)),s=Math.abs(i+e);if(!(s<.5)){var r=$.normalizeVec3(t,oi);this.eye=$.addVec3(this._look,$.mulVec3Scalar(r,s),ai)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=$.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return $.lenVec3($.subVec3(this._look,this._eye,ri))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=Ai,i=ci,s=hi;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,$.mulMat4v4(this.viewMatrix,t,i),$.mulMat4v4(this.projMatrix,i,s),$.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;var r=this.scene.canvas.canvas,n=r.offsetWidth/2,o=r.offsetHeight/2;return[s[0]*n+n,s[1]*o+o]}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),yi=function(e){g(i,we);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),t.call(this,e,s)}return C(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),bi=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r))._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var n=s.scene.camera,o=s.scene.canvas;return s._onCameraViewMatrix=n.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=n.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=o.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new qt({type:"dir",dir:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(s._shadowViewMatrixDirty){s._shadowViewMatrix||(s._shadowViewMatrix=$.identityMat4());var e=s.scene.camera,t=s._state.dir,i=e.look,r=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];$.lookAtMat4v(r,i,[0,1,0],s._shadowViewMatrix),s._shadowViewMatrixDirty=!1}return s._shadowViewMatrix},getShadowProjMatrix:function(){return s._shadowProjMatrixDirty&&(s._shadowProjMatrix||(s._shadowProjMatrix=$.identityMat4()),$.orthoMat4c(-40,40,-40,40,-40,80,s._shadowProjMatrix),s._shadowProjMatrixDirty=!1),s._shadowProjMatrix},getShadowRenderBuf:function(){return s._shadowRenderBuf||(s._shadowRenderBuf=new Wt(s.scene.canvas.canvas,s.scene.canvas.gl,{size:[1024,1024]})),s._shadowRenderBuf}}),s.dir=r.dir,s.color=r.color,s.intensity=r.intensity,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),wi=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state={type:"ambient",color:$.vec3([.7,.7,.7]),intensity:1},s.color=r.color,s.intensity=r.intensity,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),Bi=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),s=t.call(this,e,r),se.memory.meshes++,s}return C(i,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),se.memory.meshes--}}]),i}(),xi=function(){var e=[],t=[],i=[],s=[],r=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(r,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=r.length;AI)||(E=i[P.index1],F=i[P.index2],(!S&&E>65535||F>65535)&&(S=!0),k.push(E),k.push(F));return S?new Uint32Array(k):new Uint16Array(k)}}();var Pi=function(){var e=$.mat4(),t=$.mat4();return function(i,s){s=s||$.mat4();var r=i[0],n=i[1],o=i[2],a=i[3]-r,l=i[4]-n,u=i[5]-o,A=65535;return $.identityMat4(e),$.translationMat4v(i,e),$.identityMat4(t),$.scalingMat4v([a/A,l/A,u/A],t),$.mulMat4(e,t,s),s}}(),Ci=function(){var e=$.mat4(),t=$.mat4();return function(i,s,r){var n,o=new Uint16Array(i.length),a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);for(n=0;n=0?1:-1),a=(1-Math.abs(r))*(n>=0?1:-1);r=o,n=a}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function Fi(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function ki(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var Ii={getPositionsBounds:function(e){var t,i,s=new Float32Array(3),r=new Float32Array(3);for(t=0;t<3;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;s2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,s=new Float32Array(2),r=new Float32Array(2);for(t=0;t<2;t++)s[t]=Number.MAX_VALUE,r[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),s=0,r=e.length;sr&&(i=t,r=s),(s=ki(e,o,Fi(t=Ei(e,o,"floor","ceil"))))>r&&(i=t,r=s),(s=ki(e,o,Fi(t=Ei(e,o,"ceil","ceil"))))>r&&(i=t,r=s),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,s=0,r=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[s+0]=n/l,t[s+1]=o/l,t[s+2]=a/l,s+=3}return t},decompressNormal:function(e,t){var i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;var r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));var n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},Di=se.memory,Si=$.AABB3(),Ti=function(e){g(i,Bi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r))._state=new qt({compressGeometry:!!r.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._edgeIndicesBuf=null,s._pickTrianglePositionsBuf=null,s._pickTriangleColorsBuf=null,s._aabbDirty=!0,s._boundingSphere=!0,s._aabb=null,s._aabbDirty=!0,s._obb=null,s._obbDirty=!0;var n=s._state,o=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":n.primitive=o.POINTS,n.primitiveName=r.primitive;break;case"lines":n.primitive=o.LINES,n.primitiveName=r.primitive;break;case"line-loop":n.primitive=o.LINE_LOOP,n.primitiveName=r.primitive;break;case"line-strip":n.primitive=o.LINE_STRIP,n.primitiveName=r.primitive;break;case"triangles":n.primitive=o.TRIANGLES,n.primitiveName=r.primitive;break;case"triangle-strip":n.primitive=o.TRIANGLE_STRIP,n.primitiveName=r.primitive;break;case"triangle-fan":n.primitive=o.TRIANGLE_FAN,n.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),n.primitive=o.TRIANGLES,n.primitiveName=r.primitive}if(r.positions)if(s._state.compressGeometry){var a=Ii.getPositionsBounds(r.positions),l=Ii.compressPositions(r.positions,a.min,a.max);n.positions=l.quantized,n.positionsDecodeMatrix=l.decodeMatrix}else n.positions=r.positions.constructor===Float32Array?r.positions:new Float32Array(r.positions);if(r.colors&&(n.colors=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors)),r.uv)if(s._state.compressGeometry){var u=Ii.getUVBounds(r.uv),A=Ii.compressUVs(r.uv,u.min,u.max);n.uv=A.quantized,n.uvDecodeMatrix=A.decodeMatrix}else n.uv=r.uv.constructor===Float32Array?r.uv:new Float32Array(r.uv);return r.normals&&(s._state.compressGeometry?n.normals=Ii.compressNormals(r.normals):n.normals=r.normals.constructor===Float32Array?r.normals:new Float32Array(r.normals)),r.indices&&(n.indices=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3)),s._buildHash(),Di.meshes++,s._buildVBOs(),s}return C(i,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Di.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Di.positions+=e.positionsBuf.numItems),e.normals){var i=e.compressGeometry;e.normalsBuf=new Dt(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Di.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Di.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Dt(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Di.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=xi(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Di.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=$.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new Dt(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Dt(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),Di.positions+=this._pickTrianglePositionsBuf.numItems,Di.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Ii.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){var s=Ii.getPositionsBounds(e),r=Ii.compressPositions(e,s.min,s.max);e=r.quantized,t.positionsDecodeMatrix=r.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Ii.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Ii.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=$.AABB3()),$.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=$.OBB3()),$.positions3ToAABB3(this._state.positions,Si,this._state.positionsDecodeMatrix),$.AABB3ToOBB3(Si,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Di.meshes--}}]),i}();function Li(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{positions:[c,h,d,l,h,d,l,u,d,c,u,d,c,h,d,c,u,d,c,u,A,c,h,A,c,h,d,c,h,A,l,h,A,l,h,d,l,h,d,l,h,A,l,u,A,l,u,d,l,u,A,c,u,A,c,u,d,l,u,d,c,u,A,l,u,A,l,h,A,c,h,A],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var Ri=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),s=t.call(this,e,r),se.memory.materials++,s}return C(i,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),se.memory.materials--}}]),i}(),Ui={opaque:0,mask:1,blend:2},Oi=["opaque","mask","blend"],Ni=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"PhongMaterial",ambient:$.vec3([1,1,1]),diffuse:$.vec3([1,1,1]),specular:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.ambient=r.ambient,s.diffuse=r.diffuse,s.specular=r.specular,s.emissive=r.emissive,s.alpha=r.alpha,s.shininess=r.shininess,s.reflectivity=r.reflectivity,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,r.ambientMap&&(s._ambientMap=s._checkComponent("Texture",r.ambientMap)),r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.reflectivityMap&&(s._reflectivityMap=s._checkComponent("Texture",r.reflectivityMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.diffuseFresnel&&(s._diffuseFresnel=s._checkComponent("Fresnel",r.diffuseFresnel)),r.specularFresnel&&(s._specularFresnel=s._checkComponent("Fresnel",r.specularFresnel)),r.emissiveFresnel&&(s._emissiveFresnel=s._checkComponent("Fresnel",r.emissiveFresnel)),r.alphaFresnel&&(s._alphaFresnel=s._checkComponent("Fresnel",r.alphaFresnel)),r.reflectivityFresnel&&(s._reflectivityFresnel=s._checkComponent("Fresnel",r.reflectivityFresnel)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return Oi[this._state.alphaMode]},set:function(e){var t=Ui[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Qi={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Vi=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),s._preset="default",r.preset?(s.preset=r.preset,void 0!==r.fill&&(s.fill=r.fill),r.fillColor&&(s.fillColor=r.fillColor),void 0!==r.fillAlpha&&(s.fillAlpha=r.fillAlpha),void 0!==r.edges&&(s.edges=r.edges),r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth),void 0!==r.backfaces&&(s.backfaces=r.backfaces),void 0!==r.glowThrough&&(s.glowThrough=r.glowThrough)):(s.fill=r.fill,s.fillColor=r.fillColor,s.fillAlpha=r.fillAlpha,s.edges=r.edges,s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth,s.backfaces=r.backfaces,s.glowThrough=r.glowThrough),s}return C(i,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return Qi}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Qi[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Qi).join(", "))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Hi={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},ji=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),s._preset="default",r.preset?(s.preset=r.preset,r.edgeColor&&(s.edgeColor=r.edgeColor),void 0!==r.edgeAlpha&&(s.edgeAlpha=r.edgeAlpha),void 0!==r.edgeWidth&&(s.edgeWidth=r.edgeWidth)):(s.edgeColor=r.edgeColor,s.edgeAlpha=r.edgeAlpha,s.edgeWidth=r.edgeWidth),s.edges=!1!==r.edges,s}return C(i,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return Hi}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Hi[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Hi).join(", "))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Gi={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},zi=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._units="meters",s._scale=1,s._origin=$.vec3([0,0,0]),s.units=r.units,s.scale=r.scale,s.origin=r.origin,s}return C(i,[{key:"unitsInfo",get:function(){return Gi}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Gi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),Wi=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._supported=bt.SUPPORTED_EXTENSIONS.OES_standard_derivatives,s.enabled=r.enabled,s.kernelRadius=r.kernelRadius,s.intensity=r.intensity,s.bias=r.bias,s.scale=r.scale,s.minResolution=r.minResolution,s.numSamples=r.numSamples,s.blur=r.blur,s.blendCutoff=r.blendCutoff,s.blendFactor=r.blendFactor,s}return C(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Ki=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).sliceColor=r.sliceColor,s.sliceThickness=r.sliceThickness,s}return C(i,[{key:"sliceThickness",get:function(){return this._sliceThickness},set:function(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}},{key:"sliceColor",get:function(){return this._sliceColor},set:function(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Xi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},Yi=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),r.preset?(s.preset=r.preset,void 0!==r.pointSize&&(s.pointSize=r.pointSize),void 0!==r.roundPoints&&(s.roundPoints=r.roundPoints),void 0!==r.perspectivePoints&&(s.perspectivePoints=r.perspectivePoints),void 0!==r.minPerspectivePointSize&&(s.minPerspectivePointSize=r.minPerspectivePointSize),void 0!==r.maxPerspectivePointSize&&(s.maxPerspectivePointSize=r.minPerspectivePointSize)):(s._preset="default",s.pointSize=r.pointSize,s.roundPoints=r.roundPoints,s.perspectivePoints=r.perspectivePoints,s.minPerspectivePointSize=r.minPerspectivePointSize,s.maxPerspectivePointSize=r.maxPerspectivePointSize),s.filterIntensity=r.filterIntensity,s.minIntensity=r.minIntensity,s.maxIntensity=r.maxIntensity,s}return C(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Xi}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Xi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xi).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ji={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},Zi=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"LinesMaterial",lineWidth:null}),r.preset?(s.preset=r.preset,void 0!==r.lineWidth&&(s.lineWidth=r.lineWidth)):(s._preset="default",s.lineWidth=r.lineWidth),s}return C(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ji}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ji[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ji).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function qi(e,t){for(var i,s,r={},n=0,o=t.length;n1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),s=t.call(this,null,r);var n=r.canvasElement||document.getElementById(r.canvasId);if(!(n instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";s._tickifiedFunctions={};var o=!!r.transparent,a=!!r.alphaDepthMask;return s._aabbDirty=!0,s.viewer=e,s.occlusionTestCountdown=0,s.loading=0,s.startTime=(new Date).getTime(),s.models={},s.objects={},s._numObjects=0,s.visibleObjects={},s._numVisibleObjects=0,s.xrayedObjects={},s._numXRayedObjects=0,s.highlightedObjects={},s._numHighlightedObjects=0,s.selectedObjects={},s._numSelectedObjects=0,s.colorizedObjects={},s._numColorizedObjects=0,s.opacityObjects={},s._numOpacityObjects=0,s.offsetObjects={},s._numOffsetObjects=0,s._modelIds=null,s._objectIds=null,s._visibleObjectIds=null,s._xrayedObjectIds=null,s._highlightedObjectIds=null,s._selectedObjectIds=null,s._colorizedObjectIds=null,s._opacityObjectIds=null,s._offsetObjectIds=null,s._collidables={},s._compilables={},s._needRecompile=!1,s.types={},s.components={},s.sectionPlanes={},s.lights={},s.lightMaps={},s.reflectionMaps={},s.bitmaps={},s.lineSets={},s.realWorldOffset=r.realWorldOffset||new Float64Array([0,0,0]),s.canvas=new _t(b(s),{dontClear:!0,canvas:n,spinnerElementId:r.spinnerElementId,transparent:o,webgl2:!1!==r.webgl2,contextAttr:r.contextAttr||{},backgroundColor:r.backgroundColor,backgroundColorFromAmbientLight:r.backgroundColorFromAmbientLight,premultipliedAlpha:r.premultipliedAlpha}),s.canvas.on("boundary",(function(){s.glRedraw()})),s.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),s._renderer=new Yt(b(s),{transparent:o,alphaDepthMask:a}),s._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],s=0,r=t;sthis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},s._sectionPlanesState.setNumCachedSectionPlanes(r.numCachedSectionPlanes||0),s._lightsState=new function(){var e=$.vec4([0,0,0,0]),t=$.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,s=null;this.getHash=function(){if(i)return i;for(var e,t=[],s=this.lights,r=0,n=s.length;r0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(var t=0,r=this.lights.length;t1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"pickSurfacePrecisionEnabled",get:function(){return!1}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"markerZOffset",get:function(){return null==this._markerZOffset?-.001:this._markerZOffset}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&_e.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,s,r=this._passes,n=this._clearEachPass;for(i=0;in&&(n=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,s=-100,r=-100,n=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=s,this._aabb[2]=r,this._aabb[3]=n,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=qi(this,i));var s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=qi(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}},{key:"snapPick",value:function(e){return void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge)}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;to&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=$.AABB3();return u[0]=s,u[1]=r,u[2]=n,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){le.isString(e)&&(e=[e]);for(var i=!1,s=0,r=e.length;ss&&(s=r,e.apply(void 0,A(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:n},n}},{key:"destroy",value:function(){for(var e in f(w(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),es=1e3,ts=1001,is=1002,ss=1003,rs=1004,ns=1004,os=1005,as=1005,ls=1006,us=1007,As=1007,cs=1008,hs=1008,ds=1009,ps=1010,fs=1011,vs=1012,gs=1013,ms=1014,_s=1015,ys=1016,bs=1017,ws=1018,Bs=1020,xs=1021,Ps=1022,Cs=1023,Ms=1024,Es=1025,Fs=1026,ks=1027,Is=1028,Ds=1029,Ss=1030,Ts=1031,Ls=1033,Rs=33776,Us=33777,Os=33778,Ns=33779,Qs=35840,Vs=35841,Hs=35842,js=35843,Gs=36196,zs=37492,Ws=37496,Ks=37808,Xs=37809,Ys=37810,Js=37811,Zs=37812,qs=37813,$s=37814,er=37815,tr=37816,ir=37817,sr=37818,rr=37819,nr=37820,or=37821,ar=36492,lr=3e3,ur=3001,Ar=1e4,cr=10001,hr=10002,dr=10003,pr=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,n=e._state.billboard,o=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!r.compressGeometry,u=[];u.push("#version 300 es"),u.push("// Lambertian drawing vertex shader"),u.push("in vec3 position;"),u.push("uniform mat4 modelMatrix;"),u.push("uniform mat4 viewMatrix;"),u.push("uniform mat4 projMatrix;"),u.push("uniform vec4 colorize;"),u.push("uniform vec3 offset;"),l&&u.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(u.push("uniform float logDepthBufFC;"),u.push("out float vFragDepth;"),u.push("bool isPerspectiveMatrix(mat4 m) {"),u.push(" return (m[2][3] == - 1.0);"),u.push("}"),u.push("out float isPerspective;"));a&&u.push("out vec4 vWorldPosition;");if(u.push("uniform vec4 lightAmbient;"),u.push("uniform vec4 materialColor;"),u.push("uniform vec3 materialEmissive;"),r.normalsBuf){u.push("in vec3 normal;"),u.push("uniform mat4 modelNormalMatrix;"),u.push("uniform mat4 viewNormalMatrix;");for(var A=0,c=s.lights.length;A= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),u.push(" }"),u.push(" return normalize(v);"),u.push("}"))}u.push("out vec4 vColor;"),"points"===r.primitiveName&&u.push("uniform float pointSize;");"spherical"!==n&&"cylindrical"!==n||(u.push("void billboard(inout mat4 mat) {"),u.push(" mat[0][0] = 1.0;"),u.push(" mat[0][1] = 0.0;"),u.push(" mat[0][2] = 0.0;"),"spherical"===n&&(u.push(" mat[1][0] = 0.0;"),u.push(" mat[1][1] = 1.0;"),u.push(" mat[1][2] = 0.0;")),u.push(" mat[2][0] = 0.0;"),u.push(" mat[2][1] = 0.0;"),u.push(" mat[2][2] =1.0;"),u.push("}"));u.push("void main(void) {"),u.push("vec4 localPosition = vec4(position, 1.0); "),u.push("vec4 worldPosition;"),l&&u.push("localPosition = positionsDecodeMatrix * localPosition;");r.normalsBuf&&(l?u.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):u.push("vec4 localNormal = vec4(normal, 0.0); "),u.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),u.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));u.push("mat4 viewMatrix2 = viewMatrix;"),u.push("mat4 modelMatrix2 = modelMatrix;"),o&&u.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(u.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),u.push("billboard(modelMatrix2);"),u.push("billboard(viewMatrix2);"),u.push("billboard(modelViewMatrix);"),r.normalsBuf&&(u.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),u.push("billboard(modelNormalMatrix2);"),u.push("billboard(viewNormalMatrix2);"),u.push("billboard(modelViewNormalMatrix);")),u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r.normalsBuf&&u.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(u.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),u.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),u.push("float lambertian = 1.0;"),r.normalsBuf)for(var d=0,p=s.lights.length;d0,n=t.gammaOutput,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));if(r){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(var a=0,l=i.getNumAllocatedSectionPlanes();a 0.0) { discard; }"),o.push("}")}"points"===s.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)):(this.vertex=function(e){var t=e.scene;e._material;var i,s=e._state,r=t._sectionPlanesState,n=e._geometry._state,o=t._lightsState,a=s.billboard,l=s.background,u=s.stationary,A=function(e){if(!e._geometry._state.uvBuf)return!1;var t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=gr(e),h=r.getNumAllocatedSectionPlanes()>0,d=vr(e),p=!!n.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),h&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(var v=0,g=o.lights.length;v= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}A&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));n.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===n.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var m=0,_=o.lights.length;m<_;m++)o.lights[m].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+m+";"),f.push("uniform mat4 shadowProjMatrix"+m+";"),f.push("out vec4 vShadowPosFromLight"+m+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");c&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),u?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),c&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(c){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(var y=0,b=o.lights.length;y0,l=gr(e),u=s.uvBuf,A="PhongMaterial"===o.type,c="MetallicMaterial"===o.type,h="SpecularMaterial"===o.type,d=vr(e);t.gammaInput;var p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var v=0;v0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),n.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),A&&((n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = "+fr[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||h)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),n.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+fr[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),s.colors&&f.push("in vec4 vColor;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(n.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));o.ambient&&f.push("uniform vec3 materialAmbient;");o.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==o.alpha&&null!==o.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");o.emissive&&f.push("uniform vec3 materialEmissive;");o.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==o.glossiness&&null!==o.glossiness&&f.push("uniform float materialGlossiness;");void 0!==o.shininess&&null!==o.shininess&&f.push("uniform float materialShininess;");o.specular&&f.push("uniform vec3 materialSpecular;");void 0!==o.metallic&&null!==o.metallic&&f.push("uniform float materialMetallic;");void 0!==o.roughness&&null!==o.roughness&&f.push("uniform float materialRoughness;");void 0!==o.specularF0&&null!==o.specularF0&&f.push("uniform float materialSpecularF0;");u&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));u&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));u&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));u&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&u&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&u&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&u&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));u&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));u&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&u&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&u&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&u&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(var g=0,m=n.lights.length;g 0.0) { discard; }"),f.push("}")}"points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),o.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");o.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):o.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");s.colors&&f.push("diffuseColor *= vColor.rgb;");o.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");o.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==o.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");s.colors&&f.push("alpha *= vColor.a;");void 0!==o.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==o.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==o.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==o.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));u&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+fr[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));u&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+fr[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));u&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+fr[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));u&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+fr[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));u&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));u&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(n.lights.length>0||n.lightMaps.length>0||n.reflectionMaps.length>0)){u&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),u&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),u&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),u&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),u&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),u&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),u&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),A&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),h&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),n.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),A&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(h||c)&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(var w=0,B=n.lights.length;w0)for(var f=s._sectionPlanesState.sectionPlanes,v=t.renderFlags,g=0;g0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(A=0,c=n.sectionPlanes.length;A0&&n.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),this._uGammaFactor&&r.uniform1f(this._uGammaFactor,s.gammaFactor),this._baseTextureUnit=e.textureUnit};var wr=C((function e(t){x(this,e),this.vertex=function(e){var t=e.scene,i=t._lightsState,s=function(e){var t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),r=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,n=!!e._geometry._state.compressGeometry,o=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),n&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));r&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),s){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(var u=0,A=i.lights.length;u= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===o||"cylindrical"===o)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===o&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),n&&l.push("localPosition = positionsDecodeMatrix * localPosition;");s&&(n?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(var h=0,d=i.lights.length;h0,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}"points"===e._geometry._state.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var Br=new Q({}),xr=$.vec3(),Pr=function(e,t){this.id=Br.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new wr(t),this._allocate(t)},Cr={};Pr.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Cr[t];return i||(i=new Pr(t,e),Cr[t]=i,se.memory.programs++),i._useCount++,i},Pr.prototype.put=function(){0==--this._useCount&&(Br.removeItem(this.id),this._program&&this._program.destroy(),delete Cr[this._hash],se.memory.programs--)},Pr.prototype.webglContextRestored=function(){this._program=null},Pr.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s=this._scene,r=s.camera,n=s.canvas.gl,o=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(a.originHash,u):r.viewMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.clippable){var A=s._sectionPlanesState.getNumAllocatedSectionPlanes(),c=s._sectionPlanesState.sectionPlanes.length;if(A>0)for(var h=s._sectionPlanesState.sectionPlanes,d=t.renderFlags,p=0;p0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Edges drawing vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");o.push("out vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));o.push("vColor = edgeColor;"),i&&o.push("vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));s&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(r){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");s?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var Er=new Q({}),Fr=$.vec3(),kr=function(e,t){this.id=Er.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Mr(t),this._allocate(t)},Ir={};kr.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Ir[t];return i||(i=new kr(t,e),Ir[t]=i,se.memory.programs++),i._useCount++,i},kr.prototype.put=function(){0==--this._useCount&&(Er.removeItem(this.id),this._program&&this._program.destroy(),delete Ir[this._hash],se.memory.programs--)},kr.prototype.webglContextRestored=function(){this._program=null},kr.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var s,r,n=this._scene,o=n.camera,a=n.canvas.gl,l=t._state,u=t._geometry,A=u._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):o.viewMatrix),l.clippable){var h=n._sectionPlanesState.getNumAllocatedSectionPlanes(),d=n._sectionPlanesState.sectionPlanes.length;if(h>0)for(var p=n._sectionPlanesState.sectionPlanes,f=t.renderFlags,v=0;v0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh picking vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("out vec4 vViewPosition;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("uniform vec2 pickClipPos;"),o.push("vec4 remapClipPos(vec4 clipPos) {"),o.push(" clipPos.xy /= clipPos.w;"),o.push(" clipPos.xy -= pickClipPos;"),o.push(" clipPos.xy *= clipPos.w;"),o.push(" return clipPos;"),o.push("}"),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==r&&"cylindrical"!==r||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"));o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = remapClipPos(clipPos);"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = pickColor; "),r.push("}"),r}(t)}));var Sr=$.vec3(),Tr=function(e,t){this._hash=e,this._shaderSource=new Dr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Lr={};Tr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),i=Lr[t];if(!i){if((i=new Tr(t,e)).errors)return console.log(i.errors.join("\n")),null;Lr[t]=i,se.memory.programs++}return i._useCount++,i},Tr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Lr[this._hash],se.memory.programs--)},Tr.prototype.webglContextRestored=function(){this._program=null},Tr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(r.originHash,a):e.pickViewMatrix),r.clippable){var l=i._sectionPlanesState.getNumAllocatedSectionPlanes(),u=i._sectionPlanesState.sectionPlanes.length;if(l>0)for(var A=i._sectionPlanesState.sectionPlanes,c=t.renderFlags,h=0;h>24&255,b=_>>16&255,w=_>>8&255,B=255&_;s.uniform4f(this._uPickColor,B/255,w/255,b/255,y/255),s.uniform2fv(this._uPickClipPos,e.pickClipPos),o.indicesBuf?(s.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&s.drawArrays(s.TRIANGLES,0,o.positions.numItems)},Tr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new It(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0,s=!!e._geometry._state.compressGeometry,r=[];r.push("#version 300 es"),r.push("// Surface picking vertex shader"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("out vec4 vWorldPosition;"));t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;"),r.push("bool isPerspectiveMatrix(mat4 m) {"),r.push(" return (m[2][3] == - 1.0);"),r.push("}"),r.push("out float isPerspective;"));r.push("uniform vec2 pickClipPos;"),r.push("vec4 remapClipPos(vec4 clipPos) {"),r.push(" clipPos.xy /= clipPos.w;"),r.push(" clipPos.xy -= pickClipPos;"),r.push(" clipPos.xy *= clipPos.w;"),r.push(" return clipPos;"),r.push("}"),r.push("out vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push(" vec4 worldPosition = modelMatrix * localPosition; "),r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push(" vWorldPosition = worldPosition;");r.push(" vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return r.push("gl_Position = remapClipPos(clipPos);"),r.push("}"),r}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Surface picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push(" outColor = vColor;"),r.push("}"),r}(t)}));var Ur=$.vec3(),Or=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Rr(t),this._allocate(t)},Nr={};Or.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Nr[t];if(!i){if((i=new Or(t,e)).errors)return console.log(i.errors.join("\n")),null;Nr[t]=i,se.memory.programs++}return i._useCount++,i},Or.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Nr[this._hash],se.memory.programs--)},Or.prototype.webglContextRestored=function(){this._program=null},Or.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._state,n=t._material._state,o=t._geometry,a=t._geometry._state,l=t.origin,u=n.backfaces,A=n.frontface,c=i.camera.project,h=o._getPickTrianglePositions(),d=o._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){var p=2/(Math.log(c.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,p)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.originHash,l):e.pickViewMatrix),r.clippable){var f=i._sectionPlanesState.getNumAllocatedSectionPlanes(),v=i._sectionPlanesState.sectionPlanes.length;if(f>0)for(var g=i._sectionPlanesState.sectionPlanes,m=t.renderFlags,_=0;_0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh occlusion vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),s&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==r&&"cylindrical"!==r||(o.push("void billboard(inout mat4 mat) {"),o.push(" mat[0][0] = 1.0;"),o.push(" mat[0][1] = 0.0;"),o.push(" mat[0][2] = 0.0;"),"spherical"===r&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),o.push("vec4 worldPosition;"),s&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===r||"cylindrical"===r?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];r.push("#version 300 es"),r.push("// Mesh occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;"));if(s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return r.push("}"),r}(t)}));var Vr=$.vec3(),Hr=function(e,t){this._hash=e,this._shaderSource=new Qr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},jr={};Hr.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";"),i=jr[t];if(!i){if((i=new Hr(t,e)).errors)return console.log(i.errors.join("\n")),null;jr[t]=i,se.memory.programs++}return i._useCount++,i},Hr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete jr[this._hash],se.memory.programs--)},Hr.prototype.webglContextRestored=function(){this._program=null},Hr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,s=i.canvas.gl,r=t._material._state,n=t._state,o=t._geometry._state,a=t.origin;if(!(r.alpha<1)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){var l=r.backfaces;e.backfaces!==l&&(l?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=l);var u=r.frontface;e.frontface!==u&&(u?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=u),this._lastMaterialId=r.id}var A=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(n.originHash,a):A.viewMatrix),n.clippable){var c=i._sectionPlanesState.getNumAllocatedSectionPlanes(),h=i._sectionPlanesState.sectionPlanes.length;if(c>0)for(var d=i._sectionPlanesState.sectionPlanes,p=t.renderFlags,f=0;f0,i=!!e._geometry._state.compressGeometry,s=[];s.push("// Mesh shadow vertex shader"),s.push("in vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;");t&&s.push("out vec4 vWorldPosition;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;");return s.push(" gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(t),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=t._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return r.push("outColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(t)}));var zr=function(e,t){this._hash=e,this._shaderSource=new Gr(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Wr={};zr.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),s=Wr[i];if(!s){if((s=new zr(i,e)).errors)return console.log(s.errors.join("\n")),null;Wr[i]=s,se.memory.programs++}return s._useCount++,s},zr.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Wr[this._hash],se.memory.programs--)},zr.prototype.webglContextRestored=function(){this._program=null},zr.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){var n=s.backfaces;e.backfaces!==n&&(n?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=n);var o=s.frontface;e.frontface!==o&&(o?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=o),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){var a=t.vertexBufs;a.id!==this._lastVertexBufsId&&(a.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=a.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},zr.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new It(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(var r=0,n=t._sectionPlanesState.sectionPlanes.length;r0)for(var r,n,o,a=0,l=this._uSectionPlanes.length;a1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r)).originalSystemId=r.originalSystemId||s.id,s.renderFlags=new Kr,s._state=new qt({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==r.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!r.stationary,background:!!r.background,billboard:s._checkBillboard(r.billboard),layer:null,colorize:null,pickID:s.scene._renderer.getPickID(b(s)),drawHash:"",pickHash:"",offset:$.vec3(),origin:null,originHash:null}),s._drawRenderer=null,s._shadowRenderer=null,s._emphasisFillRenderer=null,s._emphasisEdgesRenderer=null,s._pickMeshRenderer=null,s._pickTriangleRenderer=null,s._occlusionRenderer=null,s._geometry=r.geometry?s._checkComponent2(["ReadableGeometry","VBOGeometry"],r.geometry):s.scene.geometry,s._material=r.material?s._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],r.material):s.scene.material,s._xrayMaterial=r.xrayMaterial?s._checkComponent("EmphasisMaterial",r.xrayMaterial):s.scene.xrayMaterial,s._highlightMaterial=r.highlightMaterial?s._checkComponent("EmphasisMaterial",r.highlightMaterial):s.scene.highlightMaterial,s._selectedMaterial=r.selectedMaterial?s._checkComponent("EmphasisMaterial",r.selectedMaterial):s.scene.selectedMaterial,s._edgeMaterial=r.edgeMaterial?s._checkComponent("EdgeMaterial",r.edgeMaterial):s.scene.edgeMaterial,s._parentNode=null,s._aabb=null,s._aabbDirty=!0,s._numTriangles=s._geometry?s._geometry.numTriangles:0,s.scene._aabbDirty=!0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._worldMatrix=$.identityMat4(),s._worldNormalMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,s._worldNormalMatrixDirty=!0;var n=r.origin||r.rtcCenter;if(n&&(s._state.origin=$.vec3(n),s._state.originHash=n.join()),r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.layer=r.layer,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.parentId){var o=s.scene.components[r.parentId];o?o.isNode?o.addChild(b(s)):s.error("Parent is not a Node: '"+r.parentId+"'"):s.error("Parent not found: '"+r.parentId+"'"),s._parentNode=o}else r.parent&&(r.parent.isNode||s.error("Parent is not a Node"),r.parent.addChild(b(s)),s._parentNode=r.parent);return s.compile(),s}return C(i,[{key:"type",get:function(){return"Mesh"}},{key:"isMesh",get:function(){return!0}},{key:"parent",get:function(){return this._parentNode}},{key:"geometry",get:function(){return this._geometry}},{key:"material",get:function(){return this._material}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=$.identityMat4()),$.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix},set:function(e){this.__localMatrix||(this.__localMatrix=$.identityMat4()),this.__localMatrix.set(e||rn),$.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._state.origin},set:function(e){e?(this._state.origin||(this._state.origin=$.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._state.visible},set:function(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}},{key:"xrayed",get:function(){return this._state.xrayed},set:function(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}},{key:"highlighted",get:function(){return this._state.highlighted},set:function(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}},{key:"selected",get:function(){return this._state.selected},set:function(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}},{key:"culled",get:function(){return this._state.culled},set:function(e){this._state.culled=!!e,this.glRedraw()}},{key:"clippable",get:function(){return this._state.clippable},set:function(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}},{key:"collidable",get:function(){return this._state.collidable},set:function(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"pickable",get:function(){return this._state.pickable},set:function(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._state.receivesShadow},set:function(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}},{key:"saoEnabled",get:function(){return!1}},{key:"colorize",get:function(){return this._state.colorize},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);var i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}},{key:"opacity",get:function(){return this._state.colorize[3]},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1);var i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}},{key:"transparent",get:function(){return 2===this._material.alphaMode||this._state.colorize[3]<1}},{key:"layer",get:function(){return this._state.layer},set:function(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}},{key:"stationary",get:function(){return this._state.stationary}},{key:"billboard",get:function(){return this._state.billboard}},{key:"offset",get:function(){return this._state.offset},set:function(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!0}},{key:"xrayMaterial",get:function(){return this._xrayMaterial}},{key:"highlightMaterial",get:function(){return this._highlightMaterial}},{key:"selectedMaterial",get:function(){return this._selectedMaterial}},{key:"edgeMaterial",get:function(){return this._edgeMaterial}},{key:"_checkBillboard",value:function(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}},{key:"compile",value:function(){var e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=yr.get(this),this._emphasisFillRenderer=Pr.get(this),this._emphasisEdgesRenderer=kr.get(this));var t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Tr.get(this)),this._state.occluder){var i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=Hr.get(this))}}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)$.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t0)for(var i=0;i-1){var L=k.geometry._state,R=k.scene,U=R.camera,O=R.canvas;if("triangles"===L.primitiveName){S.primitive="triangle";var N,Q,V,H=T,j=L.indices,G=L.positions;if(j){var z=j[H+0],W=j[H+1],K=j[H+2];n[0]=z,n[1]=W,n[2]=K,S.indices=n,N=3*z,Q=3*W,V=3*K}else V=(Q=(N=3*H)+3)+3;if(i[0]=G[N+0],i[1]=G[N+1],i[2]=G[N+2],s[0]=G[Q+0],s[1]=G[Q+1],s[2]=G[Q+2],r[0]=G[V+0],r[1]=G[V+1],r[2]=G[V+2],L.compressGeometry){var X=L.positionsDecodeMatrix;X&&(Ii.decompressPosition(i,X,i),Ii.decompressPosition(s,X,s),Ii.decompressPosition(r,X,r))}S.canvasPos?$.canvasPosToLocalRay(O.canvas,k.origin?Le(I,k.origin):I,D,k.worldMatrix,S.canvasPos,e,t):S.origin&&S.direction&&$.worldRayToLocalRay(k.worldMatrix,S.origin,S.direction,e,t),$.normalizeVec3(t),$.rayPlaneIntersect(e,t,i,s,r,o),S.localPos=o,S.position=o,v[0]=o[0],v[1]=o[1],v[2]=o[2],v[3]=1,$.transformVec4(k.worldMatrix,v,g),a[0]=g[0],a[1]=g[1],a[2]=g[2],S.canvasPos&&k.origin&&(a[0]+=k.origin[0],a[1]+=k.origin[1],a[2]+=k.origin[2]),S.worldPos=a,$.transformVec4(U.matrix,g,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],S.viewPos=l,$.cartesianToBarycentric(o,i,s,r,u),S.bary=u;var Y=L.normals;if(Y){if(L.compressGeometry){var J=3*z,Z=3*W,q=3*K;Ii.decompressNormal(Y.subarray(J,J+2),A),Ii.decompressNormal(Y.subarray(Z,Z+2),c),Ii.decompressNormal(Y.subarray(q,q+2),h)}else A[0]=Y[N],A[1]=Y[N+1],A[2]=Y[N+2],c[0]=Y[Q],c[1]=Y[Q+1],c[2]=Y[Q+2],h[0]=Y[V],h[1]=Y[V+1],h[2]=Y[V+2];var ee=$.addVec3($.addVec3($.mulVec3Scalar(A,u[0],_),$.mulVec3Scalar(c,u[1],y),b),$.mulVec3Scalar(h,u[2],w),B);S.worldNormal=$.normalizeVec3($.transformVec3(k.worldNormalMatrix,ee,x))}var te=L.uv;if(te){if(d[0]=te[2*z],d[1]=te[2*z+1],p[0]=te[2*W],p[1]=te[2*W+1],f[0]=te[2*K],f[1]=te[2*K+1],L.compressGeometry){var ie=L.uvDecodeMatrix;ie&&(Ii.decompressUV(d,ie,d),Ii.decompressUV(p,ie,p),Ii.decompressUV(f,ie,f))}S.uv=$.addVec3($.addVec3($.mulVec2Scalar(d,u[0],P),$.mulVec2Scalar(p,u[1],C),M),$.mulVec2Scalar(f,u[2],E),F)}}}}}();function an(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);var i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);var s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);var r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);var n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);var o,a,l,u,A,c,h,d,p,f,v,g=!!e.openEnded,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=s/2,B=s/n,x=2*Math.PI/r,P=1/r,C=(t-i)/n,M=[],E=[],F=[],k=[],I=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(o=0;o<=n;o++)for(A=t-o*C,c=w-o*B,a=0;a<=r;a++)l=Math.sin(a*x),u=Math.cos(a*x),E.push(A*l),E.push(I),E.push(A*u),F.push(a*P),F.push(1*o/n),M.push(A*l+_),M.push(c+y),M.push(A*u+b);for(o=0;o0){for(p=M.length/3,E.push(0),E.push(1),E.push(0),F.push(.5),F.push(.5),M.push(0+_),M.push(w+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,E.push(t*l),E.push(1),E.push(t*u),F.push(f),F.push(v),M.push(t*l+_),M.push(w+y),M.push(t*u+b);for(a=0;a0){for(p=M.length/3,E.push(0),E.push(-1),E.push(0),F.push(.5),F.push(.5),M.push(0+_),M.push(0-w+y),M.push(0+b),a=0;a<=r;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,E.push(i*l),E.push(-1),E.push(i*u),F.push(f),F.push(v),M.push(i*l+_),M.push(0-w+y),M.push(i*u+b);for(a=0;a0&&void 0!==arguments[0]?arguments[0]:{},t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0,n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);var o=e.heightSegments||18;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),(o=Math.floor(t*o))<18&&(o=18);var a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);var l,u,A,c,h,d,p,f,v,g,m,_,y,b,w=[],B=[],x=[],P=[];for(l=0;l<=o;l++)for(A=l*Math.PI/o,c=Math.sin(A),h=Math.cos(A),u=0;u<=a;u++)d=2*u*Math.PI/a,p=Math.sin(d),f=Math.cos(d)*c,v=h,g=p*c,m=1-u/a,_=l/o,B.push(f),B.push(v),B.push(g),x.push(m),x.push(_),w.push(i+n*f),w.push(s+n*v),w.push(r+n*g);for(l=0;l":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function An(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],n=e.size||1,o=[],a=[],l=e.text;le.isNumeric(l)&&(l=""+l);for(var u,A,c,h,d,p,f,v,g,m=(l||"").split("\n"),_=0,y=0,b=.04,w=0;w1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({active:!0,pos:$.vec3(),dir:$.vec3(),dist:0}),s.active=r.active,s.pos=r.pos,s.dir=r.dir,s.scene._sectionPlaneCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){$.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),dn=$.vec4(4),pn=$.vec4(),fn=$.vec4(),vn=$.vec3([1,0,0]),gn=$.vec3([0,1,0]),mn=$.vec3([0,0,1]),_n=$.vec3(3),yn=$.vec3(3),bn=$.identityMat4(),wn=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,e,r))._parentNode=null,s._children=[],s._aabb=null,s._aabbDirty=!0,s.scene._aabbDirty=!0,s._numTriangles=0,s._scale=$.vec3(),s._quaternion=$.identityQuaternion(),s._rotation=$.vec3(),s._position=$.vec3(),s._offset=$.vec3(),s._localMatrix=$.identityMat4(),s._worldMatrix=$.identityMat4(),s._localMatrixDirty=!0,s._worldMatrixDirty=!0,r.matrix?s.matrix=r.matrix:(s.scale=r.scale,s.position=r.position,r.quaternion||(s.rotation=r.rotation)),s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._isObject=r.isObject,s._isObject&&s.scene._registerObject(b(s)),s.origin=r.origin,s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.offset=r.offset,r.children)for(var n=r.children,o=0,a=n.length;o1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"LambertMaterial",ambient:$.vec3([1,1,1]),color:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),s.ambient=r.ambient,s.color=r.color,s.emissive=r.emissive,s.alpha=r.alpha,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s.backfaces=r.backfaces,s.frontface=r.frontface,s}return C(i,[{key:"type",get:function(){return"LambertMaterial"}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){var t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),xn={opaque:0,mask:1,blend:2},Pn=["opaque","mask","blend"],Cn=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"MetallicMaterial",baseColor:$.vec4([1,1,1]),emissive:$.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.baseColor=r.baseColor,s.metallic=r.metallic,s.roughness=r.roughness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.baseColorMap&&(s._baseColorMap=s._checkComponent("Texture",r.baseColorMap)),r.metallicMap&&(s._metallicMap=s._checkComponent("Texture",r.metallicMap)),r.roughnessMap&&(s._roughnessMap=s._checkComponent("Texture",r.roughnessMap)),r.metallicRoughnessMap&&(s._metallicRoughnessMap=s._checkComponent("Texture",r.metallicRoughnessMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"MetallicMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"baseColor",get:function(){return this._state.baseColor},set:function(e){var t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"baseColorMap",get:function(){return this._baseColorMap}},{key:"metallic",get:function(){return this._state.metallic},set:function(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}},{key:"metallicMap",get:function(){return this._attached.metallicMap}},{key:"roughness",get:function(){return this._state.roughness},set:function(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}},{key:"roughnessMap",get:function(){return this._attached.roughnessMap}},{key:"metallicRoughnessMap",get:function(){return this._attached.metallicRoughnessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._attached.emissiveMap}},{key:"occlusionMap",get:function(){return this._attached.occlusionMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._attached.alphaMap}},{key:"normalMap",get:function(){return this._attached.normalMap}},{key:"alphaMode",get:function(){return Pn[this._state.alphaMode]},set:function(e){var t=xn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Mn={opaque:0,mask:1,blend:2},En=["opaque","mask","blend"],Fn=function(e){g(i,Ri);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({type:"SpecularMaterial",diffuse:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),specular:$.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),s.diffuse=r.diffuse,s.specular=r.specular,s.glossiness=r.glossiness,s.specularF0=r.specularF0,s.emissive=r.emissive,s.alpha=r.alpha,r.diffuseMap&&(s._diffuseMap=s._checkComponent("Texture",r.diffuseMap)),r.emissiveMap&&(s._emissiveMap=s._checkComponent("Texture",r.emissiveMap)),r.specularMap&&(s._specularMap=s._checkComponent("Texture",r.specularMap)),r.glossinessMap&&(s._glossinessMap=s._checkComponent("Texture",r.glossinessMap)),r.specularGlossinessMap&&(s._specularGlossinessMap=s._checkComponent("Texture",r.specularGlossinessMap)),r.occlusionMap&&(s._occlusionMap=s._checkComponent("Texture",r.occlusionMap)),r.alphaMap&&(s._alphaMap=s._checkComponent("Texture",r.alphaMap)),r.normalMap&&(s._normalMap=s._checkComponent("Texture",r.normalMap)),s.alphaMode=r.alphaMode,s.alphaCutoff=r.alphaCutoff,s.backfaces=r.backfaces,s.frontface=r.frontface,s.lineWidth=r.lineWidth,s.pointSize=r.pointSize,s._makeHash(),s}return C(i,[{key:"type",get:function(){return"SpecularMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specularMap",get:function(){return this._specularMap}},{key:"specularGlossinessMap",get:function(){return this._specularGlossinessMap}},{key:"glossiness",get:function(){return this._state.glossiness},set:function(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}},{key:"glossinessMap",get:function(){return this._glossinessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"normalMap",get:function(){return this._normalMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"alphaMode",get:function(){return En[this._state.alphaMode]},set:function(e){var t=Mn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function kn(e,t){var i,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===s){var n=Xt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===n)return null;if(33776===r)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(null===(i=Xt(e,"WEBGL_compressed_texture_s3tc")))return null;if(33776===r)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){var o=Xt(e,"WEBGL_compressed_texture_pvrtc");if(null===o)return null;if(35840===r)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){var a=Xt(e,"WEBGL_compressed_texture_etc1");return null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){var l=Xt(e,"WEBGL_compressed_texture_etc");if(null===l)return null;if(37492===r)return 3001===s?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===s?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){var u=Xt(e,"WEBGL_compressed_texture_astc");if(null===u)return null;if(37808===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:u.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:u.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:u.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:u.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:u.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:u.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:u.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:u.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:u.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:u.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:u.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:u.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:u.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===s?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:u.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){var A=Xt(e,"EXT_texture_compression_bptc");if(null===A)return null;if(36492===r)return 3001===s?A.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:A.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}var In=new Uint8Array([0,0,0,1]),Dn=function(){function e(t){var i=t.gl,s=t.target,r=t.format,n=t.type,o=t.wrapS,a=t.wrapT,l=t.wrapR,u=t.encoding,A=t.preloadColor,c=t.premultiplyAlpha,h=t.flipY;x(this,e),this.gl=i,this.target=s||i.TEXTURE_2D,this.format=r||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!h,this.unpackAlignment=4,this.wrapS=o||1e3,this.wrapT=a||1e3,this.wrapR=l||1e3,this.encoding=u||3001,this.texture=i.createTexture(),A&&this.setPreloadColor(A),this.allocated=!0}return C(e,[{key:"setPreloadColor",value:function(e){e?(In[0]=Math.floor(255*e[0]),In[1]=Math.floor(255*e[1]),In[2]=Math.floor(255*e[2]),In[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(In[0]=0,In[1]=0,In[2]=0,In[3]=255);var t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP)for(var i=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z],s=0,r=i.length;s1&&void 0!==arguments[1]?arguments[1]:{},i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);var s=!1;i.bindTexture(this.target,this.texture);var r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);var n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var o=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);var a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);var l=kn(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(s=!0);var u=kn(i,this.magFilter);u&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,u);var A=kn(i,this.wrapS);A&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,A);var c=kn(i,this.wrapT);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,c);var h=kn(i,this.format,this.encoding),d=kn(i,this.type),p=Sn(i,this.internalFormat,h,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(le.isArray(e))for(var f=e,v=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z],g=0,m=v.length;g1;r.pixelStorei(r.UNPACK_FLIP_Y_WEBGL,this.flipY),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),r.pixelStorei(r.UNPACK_ALIGNMENT,this.unpackAlignment),r.pixelStorei(r.UNPACK_COLORSPACE_CONVERSION_WEBGL,r.NONE);var a=kn(r,this.wrapS);a&&r.texParameteri(this.target,r.TEXTURE_WRAP_S,a);var l=kn(r,this.wrapT);if(l&&r.texParameteri(this.target,r.TEXTURE_WRAP_T,l),this.type===r.TEXTURE_3D||this.type===r.TEXTURE_2D_ARRAY){var u=kn(r,this.wrapR);u&&r.texParameteri(this.target,r.TEXTURE_WRAP_R,u),r.texParameteri(this.type,r.TEXTURE_WRAP_R,u)}o?(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,Tn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,Tn(r,this.magFilter))):(r.texParameteri(this.target,r.TEXTURE_MIN_FILTER,kn(r,this.minFilter)),r.texParameteri(this.target,r.TEXTURE_MAG_FILTER,kn(r,this.magFilter)));var A=kn(r,this.format,this.encoding),c=kn(r,this.type),h=Sn(r,this.internalFormat,A,c,this.encoding,!1);r.texStorage2D(r.TEXTURE_2D,n,h,t[0].width,t[0].height);for(var d=0,p=t.length;d5&&void 0!==arguments[5]&&arguments[5];if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}var o=i;return i===e.RED&&(s===e.FLOAT&&(o=e.R32F),s===e.HALF_FLOAT&&(o=e.R16F),s===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RG&&(s===e.FLOAT&&(o=e.RG32F),s===e.HALF_FLOAT&&(o=e.RG16F),s===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(o=e.RGBA32F),s===e.HALF_FLOAT&&(o=e.RGBA16F),s===e.UNSIGNED_BYTE&&(o=3001===r&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)),o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||Xt(e,"EXT_color_buffer_float"),o}function Tn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Ln(e){if(!Rn(e.width)||!Rn(e.height)){var t=document.createElement("canvas");t.width=Un(e.width),t.height=Un(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Rn(e){return 0==(e&e-1)}function Un(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var On=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({texture:new Dn({gl:s.scene.canvas.gl}),matrix:$.identityMat4(),hasMatrix:r.translate&&(0!==r.translate[0]||0!==r.translate[1])||!!r.rotate||r.scale&&(0!==r.scale[0]||0!==r.scale[1]),minFilter:s._checkMinFilter(r.minFilter),magFilter:s._checkMagFilter(r.magFilter),wrapS:s._checkWrapS(r.wrapS),wrapT:s._checkWrapT(r.wrapT),flipY:s._checkFlipY(r.flipY),encoding:s._checkEncoding(r.encoding)}),s._src=null,s._image=null,s._translate=$.vec2([0,0]),s._scale=$.vec2([1,1]),s._rotate=$.vec2([0,0]),s._matrixDirty=!1,s.translate=r.translate,s.scale=r.scale,s.rotate=r.rotate,r.src?s.src=r.src:r.image&&(s.image=r.image),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"Texture"}},{key:"_checkMinFilter",value:function(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}},{key:"_checkMagFilter",value:function(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}},{key:"_checkWrapS",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkWrapT",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this._state.texture=new Dn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}},{key:"_update",value:function(){var e,t,i=this._state;this._matrixDirty&&(0===this._translate[0]&&0===this._translate[1]||(e=$.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(t=$.scalingMat4v([this._scale[0],this._scale[1],1]),e=e?$.mulMat4(e,t):t),0!==this._rotate&&(t=$.rotationMat4v(.0174532925*this._rotate,[0,0,1]),e=e?$.mulMat4(e,t):t),e&&(i.matrix=e),this._matrixDirty=!1);this.glRedraw()}},{key:"image",get:function(){return this._image},set:function(e){this._image=Ln(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}},{key:"src",get:function(){return this._src},set:function(e){this.scene.loading++,this.scene.canvas.spinner.processes++;var t=this,i=new Image;i.onload=function(){i=Ln(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}},{key:"translate",get:function(){return this._translate},set:function(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}},{key:"rotate",get:function(){return this._rotate},set:function(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}},{key:"minFilter",get:function(){return this._state.minFilter}},{key:"magFilter",get:function(){return this._state.magFilter}},{key:"wrapS",get:function(){return this._state.wrapS}},{key:"wrapT",get:function(){return this._state.wrapT}},{key:"flipY",get:function(){return this._state.flipY}},{key:"encoding",get:function(){return this._state.encoding}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),se.memory.textures--}}]),i}(),Nn=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._state=new qt({edgeColor:$.vec3([0,0,0]),centerColor:$.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),s.edgeColor=r.edgeColor,s.centerColor=r.centerColor,s.edgeBias=r.edgeBias,s.centerBias=r.centerBias,s.power=r.power,s}return C(i,[{key:"type",get:function(){return"Fresnel"}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}},{key:"centerColor",get:function(){return this._state.centerColor},set:function(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}},{key:"edgeBias",get:function(){return this._state.edgeBias},set:function(e){this._state.edgeBias=e||0,this.glRedraw()}},{key:"centerBias",get:function(){return this._state.centerBias},set:function(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}},{key:"power",get:function(){return this._state.power},set:function(e){this._state.power=null!=e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Qn=se.memory,Vn=$.AABB3(),Hn=function(e){g(i,Bi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r))._state=new qt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),s._numTriangles=0,s._edgeThreshold=r.edgeThreshold||10,s._aabb=null,s._obb=$.OBB3();var n,o=s._state,a=s.scene.canvas.gl;switch(r.primitive=r.primitive||"triangles",r.primitive){case"points":o.primitive=a.POINTS,o.primitiveName=r.primitive;break;case"lines":o.primitive=a.LINES,o.primitiveName=r.primitive;break;case"line-loop":o.primitive=a.LINE_LOOP,o.primitiveName=r.primitive;break;case"line-strip":o.primitive=a.LINE_STRIP,o.primitiveName=r.primitive;break;case"triangles":o.primitive=a.TRIANGLES,o.primitiveName=r.primitive;break;case"triangle-strip":o.primitive=a.TRIANGLE_STRIP,o.primitiveName=r.primitive;break;case"triangle-fan":o.primitive=a.TRIANGLE_FAN,o.primitiveName=r.primitive;break;default:s.error("Unsupported value for 'primitive': '"+r.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),o.primitive=a.TRIANGLES,o.primitiveName=r.primitive}if(!r.positions)return s.error("Config expected: positions"),y(s);if(!r.indices)return s.error("Config expected: indices"),y(s);var l=r.positionsDecodeMatrix;if(l);else{var u=Ii.getPositionsBounds(r.positions),A=Ii.compressPositions(r.positions,u.min,u.max);n=A.quantized,o.positionsDecodeMatrix=A.decodeMatrix,o.positionsBuf=new Dt(a,a.ARRAY_BUFFER,n,n.length,3,a.STATIC_DRAW),Qn.positions+=o.positionsBuf.numItems,$.positions3ToAABB3(r.positions,s._aabb),$.positions3ToAABB3(n,Vn,o.positionsDecodeMatrix),$.AABB3ToOBB3(Vn,s._obb)}if(r.colors){var c=r.colors.constructor===Float32Array?r.colors:new Float32Array(r.colors);o.colorsBuf=new Dt(a,a.ARRAY_BUFFER,c,c.length,4,a.STATIC_DRAW),Qn.colors+=o.colorsBuf.numItems}if(r.uv){var h=Ii.getUVBounds(r.uv),d=Ii.compressUVs(r.uv,h.min,h.max),p=d.quantized;o.uvDecodeMatrix=d.decodeMatrix,o.uvBuf=new Dt(a,a.ARRAY_BUFFER,p,p.length,2,a.STATIC_DRAW),Qn.uvs+=o.uvBuf.numItems}if(r.normals){var f=Ii.compressNormals(r.normals),v=o.compressGeometry;o.normalsBuf=new Dt(a,a.ARRAY_BUFFER,f,f.length,3,a.STATIC_DRAW,v),Qn.normals+=o.normalsBuf.numItems}var g=r.indices.constructor===Uint32Array||r.indices.constructor===Uint16Array?r.indices:new Uint32Array(r.indices);o.indicesBuf=new Dt(a,a.ELEMENT_ARRAY_BUFFER,g,g.length,1,a.STATIC_DRAW),Qn.indices+=o.indicesBuf.numItems;var m=xi(n,g,o.positionsDecodeMatrix,s._edgeThreshold);return s._edgeIndicesBuf=new Dt(a,a.ELEMENT_ARRAY_BUFFER,m,m.length,1,a.STATIC_DRAW),"triangles"===s._state.primitiveName&&(s._numTriangles=r.indices.length/3),s._buildHash(),Qn.meshes++,s}return C(i,[{key:"type",get:function(){return"VBOGeometry"}},{key:"isVBOGeometry",get:function(){return!0}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"aabb",get:function(){return this._aabb}},{key:"obb",get:function(){return this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Qn.meshes--}}]),i}(),jn={};function Gn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var n=jn.parse.from3DS(e).edit.objects[0].mesh,o=n.vertices,a=n.uvt,l=n.indices;r.processes--,i(le.apply(t,{primitive:"triangles",positions:o,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function zn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var n=jn.parse.fromOBJ(e),o=jn.edit.unwrap(n.i_verts,n.c_verts,3),a=jn.edit.unwrap(n.i_norms,n.c_norms,3),l=jn.edit.unwrap(n.i_uvt,n.c_uvt,2),u=new Int32Array(n.i_verts.length),A=0;A0?a:null,autoNormals:0===a.length,uv:l,indices:u}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Wn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);var r=e.center,n=r?r[0]:0,o=r?r[1]:0,a=r?r[2]:0,l=-t+n,u=-i+o,A=-s+a,c=t+n,h=i+o,d=s+a;return le.apply(e,{primitive:"lines",positions:[l,u,A,l,u,d,l,h,A,l,h,d,c,u,A,c,u,d,c,h,A,c,h,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Kn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Wn({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function Xn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);var i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1);for(var s=(t=t||10)/(i=i||10),r=t/2,n=[],o=[],a=0,l=0,u=-r;l<=i;l++,u+=s)n.push(-r),n.push(0),n.push(u),n.push(r),n.push(0),n.push(u),n.push(u),n.push(0),n.push(-r),n.push(u),n.push(0),n.push(r),o.push(a++),o.push(a++),o.push(a++),o.push(a++);return le.apply(e,{primitive:"lines",positions:n,indices:o})}function Yn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);var s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);var r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);var n,o,a,l,u,A,c,h=e.center,d=h?h[0]:0,p=h?h[1]:0,f=h?h[2]:0,v=t/2,g=i/2,m=Math.floor(s)||1,_=Math.floor(r)||1,y=m+1,b=_+1,w=t/m,B=i/_,x=new Float32Array(y*b*3),P=new Float32Array(y*b*3),C=new Float32Array(y*b*2),M=0,E=0;for(n=0;n65535?Uint32Array:Uint16Array)(m*_*6);for(n=0;n<_;n++)for(o=0;o0&&void 0!==arguments[0]?arguments[0]:{},t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;var i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);var s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);var r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);var n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);var o,a,l,u,A,c,h,d,p,f,v,g,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=[],B=[],x=[],P=[];for(d=0;d<=r;d++)for(h=0;h<=s;h++)o=h/s*n,a=.785398+d/r*Math.PI*2,_=t*Math.cos(o),y=t*Math.sin(o),l=(t+i*Math.cos(a))*Math.cos(o),u=(t+i*Math.cos(a))*Math.sin(o),A=i*Math.sin(a),w.push(l+_),w.push(u+y),w.push(A+b),x.push(1-h/s),x.push(d/r),c=$.normalizeVec3($.subVec3([l,u,A],[_,y,b],[]),[]),B.push(c[0]),B.push(c[1]),B.push(c[2]);for(d=1;d<=r;d++)for(h=1;h<=s;h++)p=(s+1)*d+h-1,f=(s+1)*(d-1)+h-1,v=(s+1)*(d-1)+h,g=(s+1)*d+h,P.push(p),P.push(f),P.push(v),P.push(v),P.push(g),P.push(p);return le.apply(e,{positions:w,normals:B,uv:x,indices:P})}function Zn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";var t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";for(var i=[],s=0;s0&&void 0!==arguments[0]?arguments[0]:{},t=e.curve.getPoints(e.divisions).map((function(e){return A(e)})).flat();return Zn({id:e.id,points:t})}jn.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},jn.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(jn.parse._buffToStr(e));window.location.href=i},jn.clone=function(e){return JSON.parse(JSON.stringify(e))},jn.bin={},jn.bin.f=new Float32Array(1),jn.bin.fb=new Uint8Array(jn.bin.f.buffer),jn.bin.rf=function(e,t){for(var i=jn.bin.f,s=jn.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},jn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},jn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},jn.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},jn.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},jn.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},jn.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},jn.parse={},jn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;sr&&(r=l),un&&(n=u),Ao&&(o=A)}return{min:{x:t,y:i,z:s},max:{x:r,y:n,z:o}}};var $n=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._type=r.type||(r.src?r.src.split(".").pop():null)||"jpg",s._pos=$.vec3(r.pos||[0,0,0]),s._up=$.vec3(r.up||[0,1,0]),s._normal=$.vec3(r.normal||[0,0,1]),s._height=r.height||1,s._origin=$.vec3(),s._rtcPos=$.vec3(),s._imageSize=$.vec2(),s._texture=new On(b(s),{flipY:!0}),s._image=new Image,"jpg"!==s._type&&"png"!==s._type&&(s.error('Unsupported type - defaulting to "jpg"'),s._type="jpg"),s._node=new wn(b(s),{matrix:$.inverseMat4($.lookAtMat4v(s._pos,$.subVec3(s._pos,s._normal,$.mat4()),s._up,$.mat4())),children:[s._bitmapMesh=new nn(b(s),{scale:[1,1,1],rotation:[-90,0,0],collidable:r.collidable,pickable:r.pickable,opacity:r.opacity,clippable:r.clippable,geometry:new Ti(b(s),Yn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ni(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0})})]}),r.image?s.image=r.image:r.src?s.src=r.src:r.imageData&&(s.imageData=r.imageData),s.scene._bitmapCreated(b(s)),s}return C(i,[{key:"visible",get:function(){return this._bitmapMesh.visible},set:function(e){this._bitmapMesh.visible=e}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}},{key:"src",get:function(){return this._image.src},set:function(e){var t=this;if(e)switch(this._image.onload=function(){t._texture.image=t._image,t._imageSize[0]=t._image.width,t._imageSize[1]=t._image.height,t._updateBitmapMeshScale()},this._image.src=e,e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}},{key:"imageData",get:function(){var e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")},set:function(e){var t=this;this._image.onload=function(){t._texture.image=image,t._imageSize[0]=image.width,t._imageSize[1]=image.height,t._updateBitmapMeshScale()},this._image.src=e}},{key:"type",get:function(){return this._type},set:function(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}},{key:"pos",get:function(){return this._pos}},{key:"normal",get:function(){return this._normal}},{key:"up",get:function(){return this._up}},{key:"height",get:function(){return this._height},set:function(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}},{key:"collidable",get:function(){return this._bitmapMesh.collidable},set:function(e){this._bitmapMesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._bitmapMesh.clippable},set:function(e){this._bitmapMesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._bitmapMesh.pickable},set:function(e){this._bitmapMesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._bitmapMesh.opacity},set:function(e){this._bitmapMesh.opacity=e}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._bitmapDestroyed(this)}},{key:"_updateBitmapMeshScale",value:function(){var e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}]),i}(),eo=$.OBB3(),to=$.OBB3(),io=$.OBB3(),so=function(){function e(t,i,s,r,n,o){var a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0;x(this,e),this.model=t,this.object=null,this.parent=null,this.transform=n,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=i,this.obb=null,this._aabbLocal=null,this._aabbWorld=$.AABB3(),this._aabbWorldDirty=!1,this.layer=a,this.portionId=l,this._color=new Uint8Array([s[0],s[1],s[2],r]),this._colorize=new Uint8Array([s[0],s[1],s[2],r]),this._colorizing=!1,this._transparent=r<255,this.numTriangles=0,this.origin=null,this.entity=null,n&&n._addMesh(this)}return C(e,[{key:"_sceneModelDirty",value:function(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}},{key:"_updateMatrix",value:function(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}},{key:"_finalize",value:function(e){this.layer.initFlags(this.portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this.layer.setVisible(this.portionId,e,this._transparent)}},{key:"_setColor",value:function(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}},{key:"_setColorize",value:function(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}},{key:"_setOpacity",value:function(e,t){var i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}},{key:"_setOffset",value:function(e){this.layer.setOffset(this.portionId,e)}},{key:"_setHighlighted",value:function(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this.layer.setXRayed(this.portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this.layer.setSelected(this.portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this.layer.setEdges(this.portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this.layer.setClippable(this.portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this.layer.setCollidable(this.portionId,e)}},{key:"_setPickable",value:function(e){this.layer.setPickable(this.portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this.layer.setCulled(this.portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,s){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"getEachVertex",value:function(e){this.layer.getEachVertex(this.portionId,e)}},{key:"aabb",get:function(){if(this._aabbWorldDirty){if($.AABB3ToOBB3(this._aabbLocal,eo),this.transform?($.transformOBB3(this.transform.worldMatrix,eo,to),$.transformOBB3(this.model.worldMatrix,to,io),$.OBB3ToAABB3(io,this._aabbWorld)):($.transformOBB3(this.model.worldMatrix,eo,to),$.OBB3ToAABB3(to,this._aabbWorld)),this.origin){var e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld},set:function(e){this._aabbLocal=e}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),ro=new(function(){function e(){x(this,e),this._uint8Arrays={},this._float32Arrays={}}return C(e,[{key:"_clear",value:function(){this._uint8Arrays={},this._float32Arrays={}}},{key:"getUInt8Array",value:function(e){var t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}},{key:"getFloat32Array",value:function(e){var t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}}]),e}()),no=0;function oo(){return no++,ro}var ao={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},lo=new Float32Array([1,1,1,1]),uo=new Float32Array([0,0,0,1]),Ao=$.vec4(),co=$.vec3(),ho=$.vec3(),po=$.mat4(),fo=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=s.instancing,n=void 0!==r&&r,o=s.edges,a=void 0!==o&&o;x(this,e),this._scene=t,this._withSAO=i,this._instancing=n,this._edges=a,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}return C(e,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){return[""]}},{key:"_buildFragmentShader",value:function(){return[""]}},{key:"_addMatricesUniformBlockLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}},{key:"_addRemapClipPosLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(t,"));")),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}},{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"setSectionPlanesStateUniforms",value:function(e){var t=this._scene,i=t.canvas.gl,s=e.model,r=e.layerIndex,n=t._sectionPlanesState.getNumAllocatedSectionPlanes(),o=t._sectionPlanesState.sectionPlanes.length;if(n>0){var a=t._sectionPlanesState.sectionPlanes,l=r*o,u=s.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(var A=0;A0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a3&&void 0!==arguments[3]?arguments[3]:{},r=s.colorUniform,n=void 0!==r&&r,o=s.incrementDrawState,a=void 0!==o&&o,l=bt.MAX_TEXTURE_IMAGE_UNITS,u=this._scene,A=u.canvas.gl,c=t._state,h=t.model,d=c.textureSet,p=c.origin,f=c.positionsDecodeMatrix,v=u._lightsState,g=u.pointsMaterial,m=h.scene.camera,_=m.viewNormalMatrix,y=m.project,b=e.pickViewMatrix||m.viewMatrix,w=h.position,B=h.rotationMatrix,x=h.rotationMatrixConjugate,P=h.worldNormalMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?A.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(c));var C=0,M=16;this._matricesUniformBlockBufferData.set(x,0);var E=0!==p[0]||0!==p[1]||0!==p[2],F=0!==w[0]||0!==w[1]||0!==w[2];if(E||F){var k=co;if(E){var I=$.transformPoint3(B,p,ho);k[0]=I[0],k[1]=I[1],k[2]=I[2]}else k[0]=0,k[1]=0,k[2]=0;k[0]+=w[0],k[1]+=w[1],k[2]+=w[2],this._matricesUniformBlockBufferData.set(Le(b,k,po),C+=M)}else this._matricesUniformBlockBufferData.set(b,C+=M);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,C+=M),this._matricesUniformBlockBufferData.set(f,C+=M),this._matricesUniformBlockBufferData.set(P,C+=M),this._matricesUniformBlockBufferData.set(_,C+=M),A.bindBuffer(A.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),A.bufferData(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,A.DYNAMIC_DRAW),A.bindBufferBase(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),A.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),u.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var D=2/(Math.log(e.pickZFar+1)/Math.LN2);A.uniform1f(this._uLogDepthBufFC,D)}this._uZFar&&A.uniform1f(this._uZFar,u.camera.project.far)}if(this._uPickInvisible&&A.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&A.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&A.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&A.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&A.uniform2f(this._uDrawingBufferSize,A.drawingBufferWidth,A.drawingBufferHeight),this._uUVDecodeMatrix&&A.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._uIntensityRange&&g.filterIntensity&&A.uniform2f(this._uIntensityRange,g.minIntensity,g.maxIntensity),this._uPointSize&&A.uniform1f(this._uPointSize,g.pointSize),this._uNearPlaneHeight){var S="ortho"===u.camera.projection?1:A.drawingBufferHeight/(2*Math.tan(.5*u.camera.perspective.fov*Math.PI/180));A.uniform1f(this._uNearPlaneHeight,S)}if(d){var T=d.colorTexture,L=d.metallicRoughnessTexture,R=d.emissiveTexture,U=d.normalsTexture,O=d.occlusionTexture;this._uColorMap&&T&&(this._program.bindTexture(this._uColorMap,T.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uMetallicRoughMap&&L&&(this._program.bindTexture(this._uMetallicRoughMap,L.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uEmissiveMap&&R&&(this._program.bindTexture(this._uEmissiveMap,R.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uNormalMap&&U&&(this._program.bindTexture(this._uNormalMap,U.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uAOMap&&O&&(this._program.bindTexture(this._uAOMap,O.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l)}if(v.reflectionMaps.length>0&&v.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,v.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),v.lightMaps.length>0&&v.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,v.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),this._withSAO){var N=u.sao,Q=N.possible;if(Q){var V=A.drawingBufferWidth,H=A.drawingBufferHeight;Ao[0]=V,Ao[1]=H,Ao[2]=N.blendCutoff,Ao[3]=N.blendFactor,A.uniform4fv(this._uSAOParams,Ao),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++}}if(n){var j=this._edges?"edgeColor":"fillColor",G=this._edges?"edgeAlpha":"fillAlpha";if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var z=u.xrayMaterial._state,W=z[j],K=z[G];A.uniform4f(this._uColor,W[0],W[1],W[2],K)}else if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var X=u.highlightMaterial._state,Y=X[j],J=X[G];A.uniform4f(this._uColor,Y[0],Y[1],Y[2],J)}else if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var Z=u.selectedMaterial._state,q=Z[j],ee=Z[G];A.uniform4f(this._uColor,q[0],q[1],q[2],ee)}else A.uniform4fv(this._uColor,this._edges?uo:lo)}this._draw({state:c,frameCtx:e,incrementDrawState:a}),A.bindVertexArray(null)}}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null,se.memory.programs--}}]),e}(),vo=function(e){g(i,fo);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return x(this,i),t.call(this,e,s,{instancing:!1,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{var n=s.pickElementsCount||i.indicesBuf.numItems,o=s.pickElementsOffset?s.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,n,i.indicesBuf.itemType,o),r&&s.drawElements++}}}]),i}(),go=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,s=t._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Triangles batching draw vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in float flags;"),t.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),r&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),t.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}]),i}(),mo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._lightsState,i=e._sectionPlanesState,s=i.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching flat-shading draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),s){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var n=0,o=i.getNumAllocatedSectionPlanes();n> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var A=0,c=i.getNumAllocatedSectionPlanes();A sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}r.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),r.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),r.push("float lambertian = 1.0;"),r.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),r.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),r.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var h=0,d=t.lights.length;h0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r){for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var o=0,a=s.getNumAllocatedSectionPlanes();o sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = newColor;"),n.push("}"),n}}]),i}(),yo=function(e){g(i,vo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!1,edges:!0})}return C(i)}(),bo=function(e){g(i,yo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),wo=function(e){g(i,yo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry edges drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),Bo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),xo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),Po=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Co=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Mo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching depth fragment shader"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),s.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),s.push("}"),s}}]),i}(),Eo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Fo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}]),i}(),ko=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Triangles batching quality draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),n.push("vFragDepth = 1.0 + clipPos.w;")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Triangles batching quality draw fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),o.push("uniform sampler2D uAOMap;"),o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),s.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching pick flat normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Do=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,s=e._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),r){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var o=0,a=s.getNumAllocatedSectionPlanes();o> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var c=0,h=s.getNumAllocatedSectionPlanes();c sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var d=0,p=i.lights.length;d0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),No=$.vec3(),Qo=$.vec3(),Vo=$.vec3(),Ho=$.vec3(),jo=$.mat4(),Go=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=No;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Qo;if(l){var m=Vo;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,jo),(f=Ho)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),zo=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Bo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new xo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Oo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Go(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new go(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new go(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new mo(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new mo(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Do(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Do(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new ko(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ko(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Mo(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Eo(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new bo(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new wo(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Bo(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Po(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Io(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xo(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Co(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Fo(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Go(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Oo(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Wo={};var Ko=65536,Xo=5e6,Yo=function(){function e(){x(this,e)}return C(e,[{key:"doublePrecisionEnabled",get:function(){return $.getDoublePrecisionEnabled()},set:function(e){$.setDoublePrecisionEnabled(e)}},{key:"maxDataTextureHeight",get:function(){return Ko},set:function(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Ko=e}},{key:"maxGeometryBatchSize",get:function(){return Xo},set:function(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Xo=e}}]),e}(),Jo=new Yo,Zo=C((function e(){x(this,e),this.maxVerts=Jo.maxGeometryBatchSize,this.maxIndices=3*Jo.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]})),qo=$.mat4(),$o=$.mat4();function ea(e,t,i){for(var s=e.length,r=new Uint16Array(s),n=t[0],o=t[1],a=t[2],l=t[3]-n,u=t[4]-o,A=t[5]-a,c=65525,h=c/l,d=c/u,p=c/A,f=function(e){return e>=0?e:0},v=0;v=0?1:-1),o=(1-Math.abs(s))*(r>=0?1:-1),s=n,r=o}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function sa(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}var ra=$.mat4(),na=$.mat4(),oa=$.vec4([0,0,0,1]),aa=$.vec3(),la=$.vec3(),ua=$.vec3(),Aa=$.vec3(),ca=$.vec3(),ha=$.vec3(),da=$.vec3(),pa=function(){function e(t){var i,s,r;x(this,e),console.info("Creating VBOBatchingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesBatchingLayer"+(t.solid?"-solid":"-surface")+(t.autoNormals?"-autonormals":"-normals")+(t.textureSet&&t.textureSet.colorTexture?"-colorTexture":"")+(t.textureSet&&t.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Wo[s])||(r=new zo(i),Wo[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Wo[s],r._destroy()}))),r),this._buffer=new Zo(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({origin:$.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:t.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)),t.uvDecodeMatrix?(this._state.uvDecodeMatrix=$.mat3(t.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,t.origin&&this._state.origin.set(t.origin),this.solid=!!t.solid}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)for(var C=0,M=o.length;C0){var E=ra;g?$.inverseMat4($.transposeMat4(g,na),E):$.identityMat4(E,E),function(e,t,i,s,r){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}var o,a,l,u,A,c=new Float32Array([0,0,0,0]),h=new Float32Array([0,0,0,0]);for(A=0;Au&&(a=o,u=l),(l=n(h,sa(o=ia(h,"floor","ceil"))))>u&&(a=o,u=l),(l=n(h,sa(o=ia(h,"ceil","ceil"))))>u&&(a=o,u=l),s[r+A+0]=a[0],s[r+A+1]=a[1],s[r+A+2]=0}(E,n,n.length,y.normals,y.normals.length)}if(u)for(var F=0,k=u.length;F0)for(var V=0,H=a.length;V0)for(var j=0,G=l.length;j0){var s=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):ea(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=$.mat4());if(e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(var r=0,n=this._portions.length;r0){var u=new Int8Array(i.normals);e.normalsBuf=new Dt(t,t.ARRAY_BUFFER,u,i.normals.length,3,t.STATIC_DRAW,!0)}if(i.colors.length>0){var A=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,A,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.uv.length>0)if(e.uvDecodeMatrix){e.uvBuf=new Dt(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,!1)}else{var c=Ii.getUVBounds(i.uv),h=Ii.compressUVs(i.uv,c.min,c.max),d=h.quantized;e.uvDecodeMatrix=$.mat3(h.decodeMatrix),e.uvBuf=new Dt(t,t.ARRAY_BUFFER,d,d.length,2,t.STATIC_DRAW,!1)}if(i.metallicRoughness.length>0){var p=new Uint8Array(i.metallicRoughness);e.metallicRoughnessBuf=new Dt(t,t.ARRAY_BUFFER,p,i.metallicRoughness.length,2,t.STATIC_DRAW,!1)}if(i.positions.length>0){var f=i.positions.length/3,v=new Float32Array(f);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,v,v.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var g=new Uint8Array(i.pickColors);e.pickColorsBuf=new Dt(t,t.ARRAY_BUFFER,g,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var m=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,m,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var _=new Uint32Array(i.indices);e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,_,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){var y=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,y,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}}},{key:"isEmpty",value:function(){return!this._state.indicesBuf}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=e,s=this._portions[i],r=4*s.vertsBaseIndex,n=4*s.numVerts,o=this._scratchMemory.getUInt8Array(n),a=t[0],l=t[1],u=t[2],A=t[3],c=0;c3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=e,a=this._portions[o],l=a.vertsBaseIndex,u=a.numVerts,A=l,c=u,h=!!(t&Qe),d=!!(t&ze),p=!!(t&We),f=!!(t&Ke),v=!!(t&Xe),g=!!(t&He),m=!!(t&Ve);r=!h||m||d||p&&!this.model.scene.highlightMaterial.glowThrough||f&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!h||m?ao.NOT_RENDERED:f?ao.SILHOUETTE_SELECTED:p?ao.SILHOUETTE_HIGHLIGHTED:d?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var _=0;_=!h||m?ao.NOT_RENDERED:f?ao.EDGES_SELECTED:p?ao.EDGES_HIGHLIGHTED:d?ao.EDGES_XRAYED:v?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED;var y=h&&!m&&g?ao.PICK:ao.NOT_RENDERED,b=t&je?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var w=A,B=A+c;wg)&&(g=x,s.set(m),r&&$.triangleNormal(d,p,f,r),v=!0)}}return v&&r&&($.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),v}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}]),e}(),fa=function(e){g(i,fo);var t=_(i);function i(e,s){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=r.edges,o=void 0!==n&&n;return x(this,i),t.call(this,e,s,{instancing:!0,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),r&&s.drawElements++)}}]),i}(),va=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t,i,s=this._scene,r=s._sectionPlanesState,n=s._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),s.entityOffsetsEnabled&&a.push("in vec3 offset;"),a.push("in vec4 modelMatrixCol0;"),a.push("in vec4 modelMatrixCol1;"),a.push("in vec4 modelMatrixCol2;"),a.push("in vec4 modelNormalMatrixCol0;"),a.push("in vec4 modelNormalMatrixCol1;"),a.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(a,!0),s.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),e=0,t=n.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),o&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),s.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),e=0,t=n.lights.length;e0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(newColor.rgb * ambient, 1.0);")):s.push(" outColor = newColor;"),s.push("}"),s}}]),i}(),ga=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=i._lightsState,n=s.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry flat-shading drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),i.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=s.getNumAllocatedSectionPlanes();a> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var A=0,c=s.getNumAllocatedSectionPlanes();A sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}for(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=r.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing fill fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = newColor;"),s.push("}"),s}}]),i}(),_a=function(e){g(i,fa);var t=_(i);function i(e,s){return x(this,i),t.call(this,e,s,{instancing:!0,edges:!0})}return C(i)}(),ya=function(e){g(i,_a);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesEmphasisRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),ba=function(e){g(i,_a);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// EdgesColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),wa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),Ba=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),xa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Pa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Ca=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}]),i}(),Ma=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Ea=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),Fa={3e3:"linearToLinear",3001:"sRGBToLinear"},ka=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.getNumAllocatedSectionPlanes()>0,r=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Instancing geometry quality drawing vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("in vec4 modelNormalMatrixCol0;"),n.push("in vec4 modelNormalMatrixCol1;"),n.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),r&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),n.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),r&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Instancing geometry quality drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),s.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=s.lights.length;a0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),o.push(" return normalize(surf_norm );"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),s.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Fa[s.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Fa[s.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),r){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=s.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Batched geometry normals fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("in vec4 vWorldPosition;"),i){s.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),s.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),s.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),s.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),s.push("}"),s}}]),i}(),Da=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i.gammaOutput,r=i._sectionPlanesState,n=i._lightsState,o=r.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),s&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),o){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(var l=0,u=r.getNumAllocatedSectionPlanes();l> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(var c=0,h=r.getNumAllocatedSectionPlanes();c sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=n.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Na=$.vec3(),Qa=$.vec3(),Va=$.vec3(),Ha=$.vec3(),ja=$.mat4(),Ga=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Na;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Qa;if(l){var m=$.transformPoint3(A,l,Va);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,ja),(f=Ha)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),za=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wa(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ba(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Oa(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ga(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new va(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new va(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new ga(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ga(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new ka(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ka(this._scene,!0)),this._pbrRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Da(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Da(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Ca(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Ma(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new ya(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ba(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wa(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new xa(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ia(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ba(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Pa(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Ea(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Oa(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Ga(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Wa={};var Ka=new Uint8Array(4),Xa=new Float32Array(1),Ya=$.vec4([0,0,0,1]),Ja=new Float32Array(3),Za=$.vec3(),qa=$.vec3(),$a=$.vec3(),el=$.vec3(),tl=$.vec3(),il=$.vec3(),sl=$.vec3(),rl=new Float32Array(4),nl=function(){function e(t){var i,s,r;x(this,e),console.info("Creating VBOInstancingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesInstancingLayer"+(t.solid?"-solid":"-surface")+(t.normals?"-normals":"-autoNormals"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Wa[s])||(r=new za(i),Wa[s]=r,r._compile(),r.eagerCreateRenders(),i.on("compile",(function(){r._compile(),r.eagerCreateRenders()})),i.on("destroyed",(function(){delete Wa[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new qt({numInstances:0,obb:$.OBB3(),origin:$.vec3(),geometry:t.geometry,textureSet:t.textureSet,pbrSupported:!1,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&this._state.origin.set(t.origin),this._finalized=!1,this.solid=!!t.solid,this.numIndices=t.geometry.numIndices}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){e.colorsBuf=new Dt(s,s.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,s.DYNAMIC_DRAW,!1),this._colors=[]}if(this._metallicRoughness.length>0){var o=new Uint8Array(this._metallicRoughness);e.metallicRoughnessBuf=new Dt(s,s.ARRAY_BUFFER,o,this._metallicRoughness.length,2,s.STATIC_DRAW,!1)}if(n>0){e.flagsBuf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(n),n,1,s.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){e.offsetsBuf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,s.DYNAMIC_DRAW,!1),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){e.positionsBuf=new Dt(s,s.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,s.STATIC_DRAW,!1),e.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){var a=new Uint8Array(t.colorsCompressed);e.colorsBuf=new Dt(s,s.ARRAY_BUFFER,a,a.length,4,s.STATIC_DRAW,!1)}if(t.uvCompressed&&t.uvCompressed.length>0){var l=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Dt(s,s.ARRAY_BUFFER,l,l.length,2,s.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Dt(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,s.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Dt(s,s.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,s.STATIC_DRAW)),this._modelMatrixCol0.length>0){var u=!1;e.modelMatrixCol0Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelMatrixCol1Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelMatrixCol2Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol1Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,s.STATIC_DRAW,u),e.modelNormalMatrixCol2Buf=new Dt(s,s.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,s.STATIC_DRAW,u),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){e.pickColorsBuf=new Dt(s,s.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,s.STATIC_DRAW,!1),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],Ka[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ka,4*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Qe),r=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!s||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:r?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!s||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:r?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(s&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?1:0)<<16,Xa[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Xa,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ja[0]=t[0],Ja[1]=t[1],Ja[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ja,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var i=this._state,s=i.geometry,r=this._portions[e];if(r)for(var n=s.quantizedPositions,o=i.origin,a=r.offset,l=o[0]+a[0],u=o[1]+a[1],A=o[2]+a[2],c=Ya,h=r.matrix,d=this.model.sceneModelMatrix,p=i.positionsDecodeMatrix,f=0,v=n.length;fm)&&(m=C,s.set(_),r&&$.triangleNormal(p,f,v,r),g=!0)}}return g&&r&&($.transformVec3(a.normalMatrix,r,r),$.transformVec3(this.model.worldNormalMatrix,r,r),$.normalizeVec3(r)),g}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}]),e}(),ol=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),r&&s.drawElements++}}]),i}(),al=function(e){g(i,ol);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),ll=function(e){g(i,ol);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines batching silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),ul=$.vec3(),Al=$.vec3(),cl=$.vec3(),hl=$.vec3(),dl=$.mat4(),pl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=ul;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Al;if(l){var m=cl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,dl),(f=hl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),fl=$.vec3(),vl=$.vec3(),gl=$.vec3(),ml=$.vec3(),_l=$.mat4(),yl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=fl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=vl;if(l){var m=gl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,_l),(f=ml)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),bl=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new al(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ll(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new pl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),wl={};var Bl=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;x(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]})),xl=function(){function e(t){var i,s,r;x(this,e),console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=wl[s])||(r=new bl(i),wl[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete wl[s],r._destroy()}))),r),this.model=t.model,this._buffer=new Bl(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=ea(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.colors.length>0){var o=i.colors.length/4,a=new Float32Array(o);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var l=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,l,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var u=new Uint32Array(i.indices);e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,u,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=t[3],A=0;A3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=2*e,a=this._portions[o],l=this._portions[o+1],u=a,A=l,c=!!(t&Qe),h=!!(t&ze),d=!!(t&We),p=!!(t&Ke),f=!!(t&He),v=!!(t&Ve);r=!c||v||h||d&&!this.model.scene.highlightMaterial.glowThrough||p&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!c||v?ao.NOT_RENDERED:p?ao.SILHOUETTE_SELECTED:d?ao.SILHOUETTE_HIGHLIGHTED:h?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var g=c&&!v&&f?ao.PICK:ao.NOT_RENDERED,m=t&je?1:0;if(s){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var _=u,y=u+A;_0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):n.push(" outColor = vColor;"),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),Ml=function(e){g(i,Pl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Lines instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = color;"),s.push("}"),s}}]),i}(),El=$.vec3(),Fl=$.vec3(),kl=$.vec3();$.vec3();var Il=$.mat4(),Dl=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=El;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Fl;if(l){var g=$.transformPoint3(A,l,kl);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Il),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Sl=$.vec3(),Tl=$.vec3(),Ll=$.vec3();$.vec3();var Rl=$.mat4(),Ul=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Sl;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Tl;if(l){var g=$.transformPoint3(A,l,Ll);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Rl),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ol=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ul(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Cl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ml(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Ul(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Nl={};var Ql=new Uint8Array(4),Vl=new Float32Array(1),Hl=new Float32Array(3),jl=new Float32Array(4),Gl=function(){function e(t){var i,s,r;x(this,e),console.info("VBOInstancingLinesLayer"),this.model=t.model,this.material=t.material,this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Nl[s])||(r=new Ol(i),Nl[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Nl[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new qt({obb:$.OBB3(),numInstances:0,origin:null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&(this._state.origin=$.vec3(t.origin)),this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){this._state.colorsBuf=new Dt(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,!1),this._colors=[]}if(r>0){this._state.flagsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(r),r,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){this._state.offsetsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){var n=new Uint8Array(i.colorsCompressed);t.colorsBuf=new Dt(e,e.ARRAY_BUFFER,n,n.length,4,e.STATIC_DRAW,!1)}if(i.positionsCompressed&&i.positionsCompressed.length>0){t.positionsBuf=new Dt(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,!1),t.positionsDecodeMatrix=$.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Dt(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){var o=!1;this._state.modelMatrixCol0Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol1Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol2Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,o),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ql[0]=t[0],Ql[1]=t[1],Ql[2]=t[2],Ql[3]=t[3],this._state.colorsBuf.setData(Ql,4*e,4)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Qe),r=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!s||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:r?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!s||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:r?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(s&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?255:0)<<16,Vl[0]=A,this._state.flagsBuf.setData(Vl,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Hl[0]=t[0],Hl[1]=t[1],Hl[2]=t[2],this._state.offsetsBuf.setData(Hl,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;jl[0]=t[0],jl[1]=t[4],jl[2]=t[8],jl[3]=t[12],this._state.modelMatrixCol0Buf.setData(jl,i),jl[0]=t[1],jl[1]=t[5],jl[2]=t[9],jl[3]=t[13],this._state.modelMatrixCol1Buf.setData(jl,i),jl[0]=t[2],jl[1]=t[6],jl[2]=t[10],jl[3]=t[14],this._state.modelMatrixCol2Buf.setData(jl,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}]),e}(),zl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,s=e.frameCtx,r=e.incrementDrawState;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),r&&s.drawArrays++}}]),i}(),Wl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,s=[];return s.push("#version 300 es"),s.push("// Points batching color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),Kl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}]),i}(),Xl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching pick mesh vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vPickColor; "),s.push("}"),s}}]),i}(),Yl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batched pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batched pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),Jl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points batching occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push(" } else {"),s.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push(" gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push(" }"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points batching occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push(" }")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}}]),i}(),Zl=$.vec3(),ql=$.vec3(),$l=$.vec3(),eu=$.vec3(),tu=$.mat4(),iu=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Zl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=ql;if(l){var m=$l;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,tu),(f=eu)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),su=$.vec3(),ru=$.vec3(),nu=$.vec3(),ou=$.vec3(),au=$.mat4(),lu=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=su;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=ru;if(l){var m=nu;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,au),(f=ou)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),uu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Wl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Kl(this._scene)),this._silhouetteRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Xl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Jl(this._scene)),this._occlusionRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new iu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new lu(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Au={};var cu=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;x(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]})),hu=function(){function e(t){x(this,e),console.info("Creating VBOBatchingPointsLayer"),this.model=t.model,this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=Au[t];return i||(i=new uu(e),Au[t]=i,i._compile(),e.on("compile",(function(){i._compile()})),e.on("destroyed",(function(){delete Au[t],i._destroy()}))),i}(t.model.scene),this._buffer=new cu(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var s=new Uint16Array(i.positions);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{var r=ea(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.STATIC_DRAW,!1)}if(i.positions.length>0){var o=i.positions.length/3,a=new Float32Array(o);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var l=new Uint8Array(i.pickColors);e.pickColorsBuf=new Dt(t,t.ARRAY_BUFFER,l,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var u=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,u,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized"}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(r),o=t[0],a=t[1],l=t[2],u=0;u0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing color vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("in float flags;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),i.filterIntensity&&s.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),i.filterIntensity&&(s.push("float intensity = float(color.a) / 255.0;"),s.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {")),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),i.filterIntensity&&s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing color fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),fu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,s){f(w(i.prototype),"drawLayer",this).call(this,e,t,s,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing silhouette vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 color;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),s.push("uniform vec4 silhouetteColor;"),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vColor;"),s.push("void main(void) {"),s.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),s.push("if (silhouetteFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing silhouette fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vColor;"),s.push("}"),s}}]),i}(),vu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick mesh vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 pickColor;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vPickColor;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),s.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick mesh fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("outColor = vPickColor; "),s.push("}"),s}}]),i}(),gu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing pick depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(s),this._addRemapClipPosLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("out vec4 vViewPosition;"),s.push("void main(void) {"),s.push("int pickFlag = int(flags) >> 12 & 0xF;"),s.push("if (pickFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push(" vFlags = flags;")),s.push(" vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),s.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing pick depth fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push(" outColor = packDepth(zNormalizedDepth); "),s.push("}"),s}}]),i}(),mu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in vec4 color;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push(" vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Points instancing occlusion vertex shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0;r 1.0) {"),s.push(" discard;"),s.push(" }")),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}}]),i}(),_u=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,s=[];return s.push("#version 300 es"),s.push("// Points instancing depth vertex shader"),s.push("uniform int renderPass;"),s.push("in vec3 position;"),e.entityOffsetsEnabled&&s.push("in vec3 offset;"),s.push("in float flags;"),s.push("in vec4 modelMatrixCol0;"),s.push("in vec4 modelMatrixCol1;"),s.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(s),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("out float vFragDepth;")),t&&(s.push("out vec4 vWorldPosition;"),s.push("out float vFlags;")),s.push("void main(void) {"),s.push("int colorFlag = int(flags) & 0xF;"),s.push("if (colorFlag != renderPass) {"),s.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags = flags;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,s=i._sectionPlanesState,r=s.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),r)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=s.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),r){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=s.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return n.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),yu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Instancing geometry depth drawing fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 1.0) {"),s.push(" discard;"),s.push(" }"),i){s.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}}]),i}(),bu=$.vec3(),wu=$.vec3(),Bu=$.vec3();$.vec3();var xu=$.mat4(),Pu=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.canvas.gl,o=r.camera,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=bu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=wu;if(l){var g=$.transformPoint3(A,l,Bu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,xu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Cu=$.vec3(),Mu=$.vec3(),Eu=$.vec3();$.vec3();var Fu=$.mat4(),ku=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Cu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Mu;if(l){var g=$.transformPoint3(A,l,Eu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Fu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Iu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new pu(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fu(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new _u(this._scene)),this._depthRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new vu(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new gu(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new mu(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new yu(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Pu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new ku(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Du={};var Su=new Uint8Array(4),Tu=new Float32Array(1),Lu=new Float32Array(3),Ru=new Float32Array(4),Uu=function(){function e(t){var i,s,r;x(this,e),console.info("VBOInstancingPointsLayer"),this.model=t.model,this.material=t.material,this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,s=i.id,(r=Du[s])||(r=new Iu(i),Du[s]=r,r._compile(),i.on("compile",(function(){r._compile()})),i.on("destroyed",(function(){delete Du[s],r._destroy()}))),r),this._aabb=$.collapseAABB3(),this._state=new qt({obb:$.OBB3(),numInstances:0,origin:t.origin?$.vec3(t.origin):null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){i.flagsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){i.offsetsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(s.positionsCompressed&&s.positionsCompressed.length>0){i.positionsBuf=new Dt(e,e.ARRAY_BUFFER,s.positionsCompressed,s.positionsCompressed.length,3,e.STATIC_DRAW,!1),i.positionsDecodeMatrix=$.mat4(s.positionsDecodeMatrix)}if(s.colorsCompressed&&s.colorsCompressed.length>0){var r=new Uint8Array(s.colorsCompressed);i.colorsBuf=new Dt(e,e.ARRAY_BUFFER,r,r.length,4,e.STATIC_DRAW,!1)}if(this._modelMatrixCol0.length>0){var n=!1;i.modelMatrixCol0Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,n),i.modelMatrixCol1Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,n),i.modelMatrixCol2Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,n),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){i.pickColorsBuf=new Dt(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,!1),this._pickColors=[]}i.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Su[0]=t[0],Su[1]=t[1],Su[2]=t[2],this._state.colorsBuf.setData(Su,3*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var s=!!(t&Qe),r=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!s||u||r||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!s||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:r?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!s||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:r?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(s&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?255:0)<<16,Tu[0]=A,this._state.flagsBuf.setData(Tu,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Lu[0]=t[0],Lu[1]=t[1],Lu[2]=t[2],this._state.offsetsBuf.setData(Lu,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Ru[0]=t[0],Ru[1]=t[4],Ru[2]=t[8],Ru[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ru,i),Ru[0]=t[1],Ru[1]=t[5],Ru[2]=t[9],Ru[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ru,i),Ru[0]=t[2],Ru[1]=t[6],Ru[2]=t[10],Ru[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ru,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK)}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),Ou=$.vec3(),Nu=$.vec3(),Qu=$.mat4(),Vu=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=Ou;if(f){var m=$.transformPoint3(c,u,Nu);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,Qu)}else p=d;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=s._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),o.drawArrays(o.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),o.drawArrays(o.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),o.drawArrays(o.LINES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// LinesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}},{key:"eagerCreateRenders",value:function(){}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Vu(this._scene,!1)),this._colorRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy()}}]),e}(),ju={};var Gu=C((function e(){x(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]})),zu=function(){function e(){x(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindLineIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),Wu=function(){function e(t,i,s,r){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;x(this,e),this._gl=t,this._texture=i,this._textureWidth=s,this._textureHeight=r,this._textureData=n}return C(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),Ku={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ku,null,4));var e=0;Object.keys(Ku).forEach((function(t){t.startsWith("size")&&(e+=Ku[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Ku.totalLines).toFixed(2)));var t={};Object.keys(Ku).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((Ku[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var Xu=function(){function e(){x(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,s,r){var n=t.length;this.numPortions=n;var o=4096,a=Math.ceil(n/512);if(0===a)throw"texture height===0";var l=new Uint8Array(16384*a);Ku.sizeDataColorsAndFlags+=l.byteLength,Ku.numberOfTextures++;for(var u=0;u>24&255,s[u]>>16&255,s[u]>>8&255,255&s[u]],32*u+16),l.set([r[u]>>24&255,r[u]>>16&255,r[u]>>8&255,255&r[u]],32*u+20);var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,A,o,a,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);Ku.sizeDataTextureOffsets+=r.byteLength,Ku.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,n,i,s,r)}},{key:"generateTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);Ku.numberOfTextures++;for(var o=0;o65536&&Ku.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/2})),(this._state.numVertices+n>4096*Ju||r+o>4096*Ju)&&Ku.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*Ju&&r+o<=4096*Ju)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/2/8)*2;Ku.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}var r=t.positionsCompressed,n=t.indices,o=this._buffer;o.positionsCompressed.push(r);var a,l=o.lenPositionsCompressed/3,u=r.length/3;o.lenPositionsCompressed+=r.length;var A,c=0;n&&(c=n.length/2,u<=256?(A=o.indices8Bits,a=o.lenIndices8Bits/2,o.lenIndices8Bits+=n.length):u<=65536?(A=o.indices16Bits,a=o.lenIndices16Bits/2,o.lenIndices16Bits+=n.length):(A=o.indices32Bits,a=o.lenIndices32Bits/2,o.lenIndices32Bits+=n.length),A.push(n));return this._state.numVertices+=u,Ku.numberOfGeometries++,{vertexBase:l,numVertices:u,numLines:c,indicesBase:a}}},{key:"_createSubPortion",value:function(e,t){var i,s=e.color,r=e.colors,n=e.opacity,o=e.meshMatrix,a=e.pickColor,l=this._buffer,u=this._state;l.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),l.perObjectInstancePositioningMatrices.push(o||tA),l.perObjectSolid.push(!!e.solid),r?l.perObjectColors.push([255*r[0],255*r[1],255*r[2],255]):s&&l.perObjectColors.push([s[0],s[1],s[2],n]),l.perObjectPickColors.push(a),l.perObjectVertexBases.push(t.vertexBase),i=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,l.perObjectIndexBaseOffsets.push(i/2-t.indicesBase);var A=this._subPortions.length;if(t.numLines>0){var c,h=2*t.numLines;t.numVertices<=256?(c=l.perLineNumberPortionId8Bits,u.numIndices8Bits+=h,Ku.totalLines8Bits+=t.numLines):t.numVertices<=65536?(c=l.perLineNumberPortionId16Bits,u.numIndices16Bits+=h,Ku.totalLines16Bits+=t.numLines):(c=l.perLineNumberPortionId32Bits,u.numIndices32Bits+=h,Ku.totalLines32Bits+=t.numLines),Ku.totalLines+=t.numLines;for(var d=0;d0&&(i.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,qu))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Qe),a=!!(t&ze),l=!!(t&We),u=!!(t&Ke),A=!!(t&He),c=!!(t&Ve);r=!o||c||a?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!o||c?ao.NOT_RENDERED:u?ao.SILHOUETTE_SELECTED:l?ao.SILHOUETTE_HIGHLIGHTED:a?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var h=o&&!c&&A?ao.PICK:ao.NOT_RENDERED,d=this._dataTextureState,p=this.model.scene.canvas.gl;qu[0]=r,qu[1]=n,qu[3]=h,d.texturePerObjectColorsAndFlags._textureData.set(qu,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,qu))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&je?255:0,r=this._dataTextureState,n=this.model.scene.canvas.gl;qu[0]=s,qu[1]=0,qu[2]=1,qu[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(qu,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,qu))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,$u))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,Zu))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){}},{key:"drawSilhouetteHighlighted",value:function(e,t){}},{key:"drawSilhouetteSelected",value:function(e,t){}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){}},{key:"drawSnap",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),sA=$.vec3(),rA=$.vec3(),nA=$.vec3();$.vec3();var oA=$.vec4(),aA=$.mat4(),lA=function(){function e(t,i){x(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=sA;if(f){var m=$.transformPoint3(c,u,rA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(r.viewMatrix,g,aA),(p=nA)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=s._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new It(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var r=i.lights,n=0,o=r.length;n0,n=[];n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("uniform vec4 lightAmbient;");for(var o=0,a=s.lights.length;o> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=s.lights.length;l0,s=[];if(s.push("#version 300 es"),s.push("// TrianglesDataTextureColorRenderer fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),i){s.push("in vec4 vWorldPosition;"),s.push("flat in uint vFlags2;");for(var r=0,n=t.getNumAllocatedSectionPlanes();r 0u;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),s.push(" discard;"),s.push(" }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&s.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push(" float viewportWidth = uSAOParams[0];"),s.push(" float viewportHeight = uSAOParams[1];"),s.push(" float blendCutoff = uSAOParams[2];"),s.push(" float blendFactor = uSAOParams[3];"),s.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture(uOcclusionTexture, uv))) * blendFactor;"),s.push(" outColor = vec4(vColor.rgb * ambient, 1.0);")):s.push(" outColor = vColor;"),s.push("}"),s}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),uA=new Float32Array([1,1,1]),AA=$.vec3(),cA=$.vec3(),hA=$.vec3();$.vec3();var dA=$.mat4(),pA=function(){function e(t,i){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=r.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=AA;if(u){var g=cA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Le(d,v,dA),(f=hA)[0]=r.eye[0]-v[0],f[1]=r.eye[1]-v[1],f[2]=r.eye[2]-v[2]}else p=d,f=r.eye;if(o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),i===ao.SILHOUETTE_XRAYED){var m=s.xrayMaterial._state,_=m.fillColor,y=m.fillAlpha;o.uniform4f(this._uColor,_[0],_[1],_[2],y)}else if(i===ao.SILHOUETTE_HIGHLIGHTED){var b=s.highlightMaterial._state,w=b.fillColor,B=b.fillAlpha;o.uniform4f(this._uColor,w[0],w[1],w[2],B)}else if(i===ao.SILHOUETTE_SELECTED){var x=s.selectedMaterial._state,P=x.fillColor,C=x.fillAlpha;o.uniform4f(this._uColor,P[0],P[1],P[2],C)}else o.uniform4fv(this._uColor,uA);if(s.logarithmicDepthBufferEnabled){var M=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,M)}var E=s._sectionPlanesState.getNumAllocatedSectionPlanes(),F=s._sectionPlanesState.sectionPlanes.length;if(E>0)for(var k=s._sectionPlanesState.sectionPlanes,I=t.layerIndex*F,D=n.renderFlags,S=0;S0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),fA=new Float32Array([0,0,0,1]),vA=$.vec3(),gA=$.vec3();$.vec3();var mA=$.mat4(),_A=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=vA;if(f){var m=$.transformPoint3(c,u,gA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,mA)}else p=d;if(o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),i===ao.EDGES_XRAYED){var _=r.xrayMaterial._state,y=_.edgeColor,b=_.edgeAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else if(i===ao.EDGES_HIGHLIGHTED){var w=r.highlightMaterial._state,B=w.edgeColor,x=w.edgeAlpha;o.uniform4f(this._uColor,B[0],B[1],B[2],x)}else if(i===ao.EDGES_SELECTED){var P=r.selectedMaterial._state,C=P.edgeColor,M=P.edgeAlpha;o.uniform4f(this._uColor,C[0],C[1],C[2],M)}else o.uniform4fv(this._uColor,fA);var E=r._sectionPlanesState.getNumAllocatedSectionPlanes(),F=r._sectionPlanesState.sectionPlanes.length;if(E>0)for(var k=r._sectionPlanesState.sectionPlanes,I=t.layerIndex*F,D=s.renderFlags,S=0;S0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),yA=$.vec3(),bA=$.vec3(),wA=$.mat4(),BA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=yA;if(f){var m=$.transformPoint3(c,u,bA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,wA)}else p=d;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=s.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),xA=$.vec3(),PA=$.vec3(),CA=$.vec3(),MA=$.mat4(),EA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate;A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==c[0]||0!==c[1]||0!==c[2],v=0!==h[0]||0!==h[1]||0!==h[2];if(f||v){var g=xA;if(f){var m=$.transformPoint3(d,c,PA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=h[0],g[1]+=h[1],g[2]+=h[2],s=Le(a.viewMatrix,g,MA),(r=CA)[0]=a.eye[0]-g[0],r[1]=a.eye[1]-g[1],r[2]=a.eye[2]-g[2]}else s=a.viewMatrix,r=a.eye;if(l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),o.logarithmicDepthBufferEnabled){var _=2/(Math.log(a.project.far+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,_)}var y=o._sectionPlanesState.getNumAllocatedSectionPlanes(),b=o._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=o._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),FA=$.vec3(),kA=$.vec3(),IA=$.vec3();$.vec3();var DA=$.mat4(),SA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=e.pickViewMatrix||a.viewMatrix;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==h[0]||0!==h[1]||0!==h[2]){var v=FA;if(c){var g=kA;$.transformPoint3(d,c,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=h[0],v[1]+=h[1],v[2]+=h[2],s=Le(f,v,DA),(r=IA)[0]=a.eye[0]-v[0],r[1]=a.eye[1]-v[1],r[2]=a.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else s=f,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(l.uniform3fv(this._uCameraEyeRtc,r),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform1f(this._uPickZNear,e.pickZNear),l.uniform1f(this._uPickZFar,e.pickZFar),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),o.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,m)}var _=o._sectionPlanesState.getNumAllocatedSectionPlanes(),y=o._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=o._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=n.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),TA=$.vec3(),LA=$.vec3(),RA=$.vec3(),UA=$.vec3();$.vec3();var OA=$.mat4(),NA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=TA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=LA;if(m){var b=$.transformPoint3(d,c,RA);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Le(v,y,OA),(r=UA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this.uVectorA,e.snapVectorA),l.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var w=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,w);var B=o._sectionPlanesState.getNumAllocatedSectionPlanes(),x=o._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=n.renderFlags,E=0;E0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),l.drawArrays(S,0,u.numEdgeIndices8Bits)),u.numEdgeIndices16Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),l.drawArrays(S,0,u.numEdgeIndices16Bits)),u.numEdgeIndices32Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),l.drawArrays(S,0,u.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),QA=$.vec3(),VA=$.vec3(),HA=$.vec3(),jA=$.vec3();$.vec3();var GA=$.mat4(),zA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var s,r,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=QA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=VA;if(m){var b=HA;$.transformPoint3(d,c,b),y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],s=Le(v,y,GA),(r=jA)[0]=a.eye[0]-y[0],r[1]=a.eye[1]-y[1],r[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else s=v,r=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,r),l.uniform2fv(this._uVectorA,e.snapVectorA),l.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,s),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var w=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,w);var B=o._sectionPlanesState.getNumAllocatedSectionPlanes(),x=o._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=n.renderFlags,E=0;E0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),WA=$.vec3(),KA=$.vec3(),XA=$.vec3();$.vec3();var YA=$.mat4(),JA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=s.position,c=s.rotationMatrix,h=s.rotationMatrixConjugate,d=e.pickViewMatrix||n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=WA;if(u){var g=KA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Le(d,v,YA),(f=XA)[0]=n.eye[0]-v[0],f[1]=n.eye[1]-v[1],f[2]=n.eye[2]-v[2]}else p=d,f=n.eye;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var m=r._sectionPlanesState.getNumAllocatedSectionPlanes(),_=r._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=r._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,w=s.renderFlags,B=0;B0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ZA=$.vec3(),qA=$.vec3(),$A=$.vec3();$.vec3();var ec=$.mat4(),tc=function(){function e(t){x(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=ZA;if(f){var m=$.transformPoint3(c,u,qA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(r.viewMatrix,g,ec),(p=$A)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=s._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ic=$.vec3(),sc=$.vec3(),rc=$.vec3();$.vec3();var nc=$.mat4(),oc=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var s=t.model,r=s.scene,n=r.camera,o=r.canvas.gl,a=t._state,l=t._state.origin,u=s.position,A=s.rotationMatrix,c=s.rotationMatrixConjugate,h=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));var f=0!==l[0]||0!==l[1]||0!==l[2],v=0!==u[0]||0!==u[1]||0!==u[2];if(f||v){var g=ic;if(f){var m=sc;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],d=Le(h,g,nc),(p=rc)[0]=n.eye[0]-g[0],p[1]=n.eye[1]-g[1],p[2]=n.eye[2]-g[2]}else d=h,p=n.eye;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,c),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);var _=r._sectionPlanesState.getNumAllocatedSectionPlanes(),y=r._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=r._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=s.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(bt.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(var s=0;s 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ac=$.vec3(),lc=$.vec3(),uc=$.vec3();$.vec3(),$.vec4();var Ac=$.mat4(),cc=function(){function e(t,i){x(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var s=this._scene,r=s.camera,n=t.model,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=ac;if(f){var m=$.transformPoint3(c,u,lc);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(r.viewMatrix,g,Ac),(p=uc)[0]=r.eye[0]-g[0],p[1]=r.eye[1]-g[1],p[2]=r.eye[2]-g[2]}else d=r.viewMatrix,p=r.eye;if(o.uniform2fv(this._uPickClipPos,e.pickClipPos),o.uniform2f(this._uDrawingBufferSize,o.drawingBufferWidth,o.drawingBufferHeight),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,r.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),s.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=s._sectionPlanesState.getNumAllocatedSectionPlanes(),b=s._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=s._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(var s=0,r=e._sectionPlanesState.getNumAllocatedSectionPlanes();s 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),hc=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new pA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new EA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new SA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new cc(this._scene)),this._snapRenderer||(this._snapRenderer=new NA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new zA(this._scene)),this._snapRenderer||(this._snapRenderer=new NA(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new lA(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new lA(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pA(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new tc(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new oc(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new _A(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new BA(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new EA(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new cc(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cc(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new SA(this._scene)),this._pickDepthRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new NA(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new zA(this._scene)),this._snapInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new JA(this._scene)),this._occlusionRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}]),e}(),dc={};var pc=C((function e(){x(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),fc=function(){function e(){x(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,s,r){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,s,3),this.texturePerObjectInstanceMatrices.bindTexture(e,r,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,s){this.indicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.indicesPerBitnessTextures[s].bindTexture(e,i,6)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,s){this.edgeIndicesPortionIdsPerBitnessTextures[s].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[s].bindTexture(e,i,6)}}]),e}(),vc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(vc,null,4));var e=0;Object.keys(vc).forEach((function(t){t.startsWith("size")&&(e+=vc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/vc.totalPolygons).toFixed(2)));var t={};Object.keys(vc).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((vc[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var gc=function(){function e(){x(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"createTextureForColorsAndFlags",value:function(e,t,i,s,r,n,o){var a=t.length;this.numPortions=a;var l=4096,u=Math.ceil(a/512);if(0===u)throw"texture height===0";var A=new Uint8Array(16384*u);vc.sizeDataColorsAndFlags+=A.byteLength,vc.numberOfTextures++;for(var c=0;c>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+16),A.set([r[c]>>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+20),A.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),A.set([o[c]?1:0,0,0,0],32*c+28);var h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,A,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,h,l,u,A)}},{key:"createTextureForObjectOffsets",value:function(e,t){var i=512,s=Math.ceil(t/i);if(0===s)throw"texture height===0";var r=new Float32Array(1536*s).fill(0);vc.sizeDataTextureOffsets+=r.byteLength,vc.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,s),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,s,e.RGB,e.FLOAT,r,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,n,i,s,r)}},{key:"createTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var s=2048,r=Math.ceil(i/512),n=new Float32Array(8192*r);vc.numberOfTextures++;for(var o=0;o65536&&vc.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,s=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[s]){var r=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/3})),(this._state.numVertices+n>4096*_c||r+o>4096*_c)&&vc.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*_c&&r+o<=4096*_c)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var s=[];t.buckets.forEach((function(e,r){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(r):"".concat(t.id,"#").concat(r),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);s.push(a)}));var r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/3/8)*3;vc.overheadSizeAlignementIndices+=2*(i-t.indices.length);var s=new Uint32Array(i);s.fill(0),s.set(t.indices),t.indices=s}if(t.edgeIndices){var r=8*Math.ceil(t.edgeIndices.length/2/8)*2;vc.overheadSizeAlignementEdgeIndices+=2*(r-t.edgeIndices.length);var n=new Uint32Array(r);n.fill(0),n.set(t.edgeIndices),t.edgeIndices=n}var o=t.positionsCompressed,a=t.indices,l=t.edgeIndices,u=this._buffer;u.positionsCompressed.push(o);var A,c=u.lenPositionsCompressed/3,h=o.length/3;u.lenPositionsCompressed+=o.length;var d,p,f=0;a&&(f=a.length/3,h<=256?(d=u.indices8Bits,A=u.lenIndices8Bits/3,u.lenIndices8Bits+=a.length):h<=65536?(d=u.indices16Bits,A=u.lenIndices16Bits/3,u.lenIndices16Bits+=a.length):(d=u.indices32Bits,A=u.lenIndices32Bits/3,u.lenIndices32Bits+=a.length),d.push(a));var v,g=0;l&&(g=l.length/2,h<=256?(v=u.edgeIndices8Bits,p=u.lenEdgeIndices8Bits/2,u.lenEdgeIndices8Bits+=l.length):h<=65536?(v=u.edgeIndices16Bits,p=u.lenEdgeIndices16Bits/2,u.lenEdgeIndices16Bits+=l.length):(v=u.edgeIndices32Bits,p=u.lenEdgeIndices32Bits/2,u.lenEdgeIndices32Bits+=l.length),v.push(l));return this._state.numVertices+=h,vc.numberOfGeometries++,{vertexBase:c,numVertices:h,numTriangles:f,numEdges:g,indicesBase:A,edgeIndicesBase:p}}},{key:"_createSubPortion",value:function(e,t,i,s){var r=e.color;e.metallic,e.roughness;var n,o,a=e.colors,l=e.opacity,u=e.meshMatrix,A=e.pickColor,c=this._buffer,h=this._state;c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(u||xc),c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):r&&c.perObjectColors.push([r[0],r[1],r[2],l]),c.perObjectPickColors.push(A),c.perObjectVertexBases.push(t.vertexBase),n=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,c.perObjectIndexBaseOffsets.push(n/3-t.indicesBase),o=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(o/2-t.edgeIndicesBase);var d=this._subPortions.length;if(t.numTriangles>0){var p,f=3*t.numTriangles;t.numVertices<=256?(p=c.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=f,vc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(p=c.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=f,vc.totalPolygons16Bits+=t.numTriangles):(p=c.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=f,vc.totalPolygons32Bits+=t.numTriangles),vc.totalPolygons+=t.numTriangles;for(var v=0;v0){var g,m=2*t.numEdges;t.numVertices<=256?(g=c.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=m,vc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=c.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=m,vc.totalEdges16Bits+=t.numEdges):(g=c.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=m,vc.totalEdges32Bits+=t.numEdges),vc.totalEdges+=t.numEdges;for(var _=0;_0&&(i.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId8Bits)),r.perEdgeNumberPortionId16Bits.length>0&&(i.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId16Bits)),r.perEdgeNumberPortionId32Bits.length>0&&(i.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(s,r.perEdgeNumberPortionId32Bits)),r.lenIndices8Bits>0&&(i.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(s,r.indices8Bits,r.lenIndices8Bits)),r.lenIndices16Bits>0&&(i.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(s,r.indices16Bits,r.lenIndices16Bits)),r.lenIndices32Bits>0&&(i.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(s,r.indices32Bits,r.lenIndices32Bits)),r.lenEdgeIndices8Bits>0&&(i.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(s,r.edgeIndices8Bits,r.lenEdgeIndices8Bits)),r.lenEdgeIndices16Bits>0&&(i.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(s,r.edgeIndices16Bits,r.lenEdgeIndices16Bits)),r.lenEdgeIndices32Bits>0&&(i.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(s,r.edgeIndices32Bits,r.lenEdgeIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,s.RGBA_INTEGER,s.UNSIGNED_BYTE,bc)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var s=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=this._portionToSubPortionsMap[e],n=0,o=r.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var r,n,o=!!(t&Qe),a=!!(t&ze),l=!!(t&We),u=!!(t&Ke),A=!!(t&Xe),c=!!(t&He),h=!!(t&Ve);r=!o||h||a||l&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!o||h?ao.NOT_RENDERED:u?ao.SILHOUETTE_SELECTED:l?ao.SILHOUETTE_HIGHLIGHTED:a?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var d=0;d=!o||h?ao.NOT_RENDERED:u?ao.EDGES_SELECTED:l?ao.EDGES_HIGHLIGHTED:a?ao.EDGES_XRAYED:A?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED;var p=o&&!h&&c?ao.PICK:ao.NOT_RENDERED,f=this._dtxState,v=this.model.scene.canvas.gl;bc[0]=r,bc[1]=n,bc[2]=d,bc[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(bc,32*e+8),this._deferredSetFlagsActive||s?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),v.bindTexture(v.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),v.texSubImage2D(v.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,v.RGBA_INTEGER,v.UNSIGNED_BYTE,bc))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],s=this._portionToSubPortionsMap[e],r=0,n=s.length;r2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var s=t&je?255:0,r=this._dtxState,n=this.model.scene.canvas.gl;bc[0]=s,bc[1]=0,bc[2]=1,bc[3]=2,r.texturePerObjectColorsAndFlags._textureData.set(bc,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,r.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,bc))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectOffsets._texture),s.texSubImage2D(s.TEXTURE_2D,0,0,e,1,1,s.RGB,s.FLOAT,wc))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],s=0,r=i.length;s=10&&this._beginDeferredFlags(),s.bindTexture(s.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),s.texSubImage2D(s.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,s.RGBA,s.FLOAT,yc))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,ao.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var s=t.gl;i?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),t.backfaces=i}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,ao.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,ao.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,ao.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),Cc=function(){function e(t){x(this,e),this.id=t.id,this.colorTexture=t.colorTexture,this.metallicRoughnessTexture=t.metallicRoughnessTexture,this.normalsTexture=t.normalsTexture,this.emissiveTexture=t.emissiveTexture,this.occlusionTexture=t.occlusionTexture}return C(e,[{key:"destroy",value:function(){}}]),e}(),Mc=function(){function e(t){x(this,e),this.id=t.id,this.texture=t.texture}return C(e,[{key:"destroy",value:function(){this.texture&&(this.texture.destroy(),this.texture=null)}}]),e}(),Ec={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={}}},Fc=function(){function e(t,i,s){x(this,e),this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=t,this.onProgress=i,this.onError=s}return C(e,[{key:"itemStart",value:function(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}},{key:"itemEnd",value:function(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}},{key:"itemError",value:function(e){void 0!==this.onError&&this.onError(e)}},{key:"resolveURL",value:function(e){return this.urlModifier?this.urlModifier(e):e}},{key:"setURLModifier",value:function(e){return this.urlModifier=e,this}},{key:"addHandler",value:function(e,t){return this.handlers.push(e,t),this}},{key:"removeHandler",value:function(e){var t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}},{key:"getHandler",value:function(e){for(var t=0,i=this.handlers.length;t0&&void 0!==arguments[0]?arguments[0]:4;x(this,e),this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}return C(e,[{key:"_initWorker",value:function(e){if(!this.workers[e]){var t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}},{key:"_getIdleWorker",value:function(){for(var e=0;e0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Lc++}return this._transcoderPending}},{key:"transcode",value:function(e,t){var i=this,s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((function(r,n){var o=s;i._init().then((function(){return i._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e)})).then((function(e){var i=e.data,s=i.mipmaps,o=(i.width,i.height,i.format),a=i.type,l=i.error,u=i.dfdTransferFn,A=i.dfdFlags;if("error"===a)return n(l);t.setCompressedData({mipmaps:s,props:{format:o,minFilter:1===s.length?1006:1008,magFilter:1===s.length?1006:1008,encoding:2===u?3001:3e3,premultiplyAlpha:!!(1&A)}}),r()}))}))}},{key:"destroy",value:function(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Lc--}}]),e}();Rc.BasisFormat={ETC1S:0,UASTC_4x4:1},Rc.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},Rc.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},Rc.BasisWorker=function(){var e,t,i,s=_EngineFormat,r=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(o){var A,c=o.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((function(e){i={wasmBinary:A,onRuntimeInitialized:e},BASIS(i)})).then((function(){i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((function(){try{for(var t=function(t){var o=new i.KTX2File(new Uint8Array(t));function A(){o.close(),o.delete()}if(!o.isValid())throw A(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");var c=o.isUASTC()?n.UASTC_4x4:n.ETC1S,h=o.getWidth(),d=o.getHeight(),p=o.getLevels(),f=o.getHasAlpha(),v=o.getDFDTransferFunc(),g=o.getDFDFlags(),m=function(t,i,o,A){for(var c,h,d=t===n.ETC1S?a:l,p=0;p=0;--s){var n=this.tryEntries[s],o=n.completion;if("root"===n.tryLoc)return r("end");if(n.tryLoc<=this.prev){var a=i.call(n,"catchLoc"),l=i.call(n,"finallyLoc");if(a&&l){if(this.prev=0;--r){var s=this.tryEntries[r];if(s.tryLoc<=this.prev&&i.call(s,"finallyLoc")&&this.prev=0;--t){var i=this.tryEntries[t];if(i.finallyLoc===e)return this.complete(i.completion,i.afterLoc),x(i),c}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var i=this.tryEntries[t];if(i.tryLoc===e){var r=i.completion;if("throw"===r.type){var s=r.arg;x(i)}return s}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,i){return this.delegate={iterator:C(e),resultName:t,nextLoc:i},"next"===this.method&&(this.arg=void 0),c}},e}function l(e,t,i,r,s,n,o){try{var a=e[n](o),l=a.value}catch(e){return void i(e)}a.done?t(l):Promise.resolve(l).then(r,s)}function u(e){return function(){var t=this,i=arguments;return new Promise((function(r,s){var n=e.apply(t,i);function o(e){l(n,r,s,o,a,"next",e)}function a(e){l(n,r,s,o,a,"throw",e)}o(void 0)}))}}function A(e){return function(e){if(Array.isArray(e))return p(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||d(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=d(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var r=0,s=function(){};return{s:s,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n,o=!0,a=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){a=!0,n=e},f:function(){try{o||null==i.return||i.return()}finally{if(a)throw n}}}}function h(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var r,s,n=[],o=!0,a=!1;try{for(i=i.call(e);!(o=(r=i.next()).done)&&(n.push(r.value),!t||n.length!==t);o=!0);}catch(e){a=!0,s=e}finally{try{o||null==i.return||i.return()}finally{if(a)throw s}}return n}(e,t)||d(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function d(e,t){if(e){if("string"==typeof e)return p(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?p(e,t):void 0}}function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,r=new Array(t);i0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this._id=V.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==i.hideOnMouseDown&&(document.addEventListener("mousedown",(function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),document.addEventListener("touchstart",this._canvasTouchStartHandler=function(e){e.target.classList.contains("xeokit-context-menu-item")||t.hide()})),i.items&&(this.items=i.items),this._hideOnAction=!1!==i.hideOnAction,this.context=i.context,this.enabled=!1!==i.enabled,this.hide()}return C(e,[{key:"on",value:function(e,t){var i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}},{key:"fire",value:function(e,t){var i=this._eventSubs[e];if(i)for(var r=0,s=i.length;r0,A=t._getNextId(),c=n.getTitle||function(){return n.title||""},h=n.doAction||n.callback||function(){},d=n.getEnabled||function(){return!0},p=n.getShown||function(){return!0},f=new G(A,c,h,d,p);if(f.parentMenu=s,l.items.push(f),u){var v=e(o);f.subMenu=v,v.parentItem=f}t._itemList.push(f),t._itemMap[f.id]=f},A=0,c=a.length;A'),r.push("
    "),i)for(var s=0,n=i.length;s'+d+" [MORE]"):r.push('
  • '+d+"
  • ")}}r.push("
"),r.push("");var p=r.join("");document.body.insertAdjacentHTML("beforeend",p);var f=document.querySelector("."+e.id);e.menuElement=f,f.style["border-radius"]="4px",f.style.display="none",f.style["z-index"]=3e5,f.style.background="white",f.style.border="1px solid black",f.style["box-shadow"]="0 4px 5px 0 gray",f.oncontextmenu=function(e){e.preventDefault()};var v=this,g=null;if(i)for(var m=0,_=i.length;m<_;m++){var y=i[m].items;if(y)for(var b=function(e,i){var r=y[e],s=r.subMenu;if(r.itemElement=document.getElementById(r.id),!r.itemElement)return console.error("ContextMenu item element not found: "+r.id),"continue";r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault();var t=r.subMenu;if(t){if(g&&g.id!==t.id&&(v._hideMenu(g.id),g=null),!1!==r.enabled){var i=r.itemElement,s=t.menuElement,n=i.getBoundingClientRect();s.getBoundingClientRect();n.right+200>window.innerWidth?v._showMenu(t.id,n.left-200,n.top-1):v._showMenu(t.id,n.right-5,n.top-1),g=t}}else g&&(v._hideMenu(g.id),g=null)})),s||(r.itemElement.addEventListener("click",(function(e){e.preventDefault(),v._context&&!1!==r.enabled&&(r.doAction&&r.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus()))})),r.itemElement.addEventListener("mouseup",(function(e){3===e.which&&(e.preventDefault(),v._context&&!1!==r.enabled&&(r.doAction&&r.doAction(v._context),t._hideOnAction?v.hide():(v._updateItemsTitles(),v._updateItemsEnabledStatus())))})),r.itemElement.addEventListener("mouseenter",(function(e){e.preventDefault(),!1!==r.enabled&&r.doHover&&r.doHover(v._context)})))},w=0,B=y.length;wwindow.innerHeight&&(i=window.innerHeight-r),t+s>window.innerWidth&&(t=window.innerWidth-s),e.style.left=t+"px",e.style.top=i+"px"}},{key:"_hideMenuElement",value:function(e){e.style.display="none"}}]),e}(),W=function(){function e(t){var i=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.viewer=t,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._lensCursorDiv,this.viewer.scene.canvas.canvas),this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red",this._lensCursorDiv.style.borderRadius="20px",this._lensCursorDiv.style.width="10px",this._lensCursorDiv.style.height="10px",this._lensCursorDiv.style.margin="-200px -200px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width="300px",this._lensContainer.style.height="300px",this._lensContainer.style.marginTop="85px",this._lensContainer.style.marginLeft="25px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width="300px",this._lensCanvas.style.height="300px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=!0,this._zoomLevel=r.zoomLevel||2,this._active=!1!==r.active,this._visible=!1,this._snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(function(){i._active&&i._visible&&i.update()}))}return C(e,[{key:"update",value:function(){if(this._active&&this._visible&&this._canvasPos){var e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]e.left&&this._canvasPos[1]e.top;this._lensContainer.style.marginLeft="25px",i&&(this._lensPosToggle?this._lensContainer.style.marginTop="".concat(t.bottom-t.top-this._lensCanvas.height-85,"px"):this._lensContainer.style.marginTop="85px",this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);var r=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-r/2,this._canvasPos[1]-r/2,r,r,0,0,this._lensCanvas.width,this._lensCanvas.height);var s=[(e.left+e.right)/2-t.left,(e.top+e.bottom)/2-t.top];if(this._snappedCanvasPos){var n=this._snappedCanvasPos[0]-this._canvasPos[0],o=this._snappedCanvasPos[1]-this._canvasPos[1];this._lensCursorDiv.style.marginLeft="".concat(s[0]+n*this._zoomLevel-10,"px"),this._lensCursorDiv.style.marginTop="".concat(s[1]+o*this._zoomLevel-10,"px")}else this._lensCursorDiv.style.marginLeft="".concat(s[0]-10,"px"),this._lensCursorDiv.style.marginTop="".concat(s[1]-10,"px")}}},{key:"zoomFactor",get:function(){return this._zoomFactor},set:function(e){this._zoomFactor=e,this.update()}},{key:"canvasPos",get:function(){return this._canvasPos},set:function(e){this._canvasPos=e,this.update()}},{key:"snappedCanvasPos",get:function(){return this._snappedCanvasPos},set:function(e){this._snappedCanvasPos=e,this.update()}},{key:"snapped",get:function(){return this._snapped},set:function(e){this._snapped=e,e?(this._lensCursorDiv.style.background="greenyellow",this._lensCursorDiv.style.border="2px solid green"):(this._lensCursorDiv.style.background="pink",this._lensCursorDiv.style.border="2px solid red")}},{key:"active",get:function(){return this._active},set:function(e){this._active=e,this._lensContainer.style.visibility=e&&this._visible?"visible":"hidden",e&&this._visible||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=e,this._lensContainer.style.visibility=e&&this._active?"visible":"hidden",e&&this._active||(this._lensCursorDiv.style.marginLeft="-100px",this._lensCursorDiv.style.marginTop="-100px"),this.update()}},{key:"destroy",value:function(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}]),e}(),K=!0,X=K?Float64Array:Float32Array,Y=new X(3),J=new X(16),Z=new X(16),q=new X(4),$={setDoublePrecisionEnabled:function(e){X=(K=e)?Float64Array:Float32Array},getDoublePrecisionEnabled:function(){return K},MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId:function(e,t){var i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:function(e,t){return e+"#"+t},safeInv:function(e){var t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:function(e){return new X(e||2)},vec3:function(e){return new X(e||3)},vec4:function(e){return new X(e||4)},mat3:function(e){return new X(e||9)},mat3ToMat4:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new X(16);return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},mat4:function(e){return new X(e||16)},mat4ToMat3:function(e,t){},doublesToFloats:function(e,t,i){for(var r=new X(2),s=0,n=e.length;s>8&255]+e[t>>16&255]+e[t>>24&255],"-").concat(e[255&i]).concat(e[i>>8&255],"-").concat(e[i>>16&15|64]).concat(e[i>>24&255],"-").concat(e[63&r|128]).concat(e[r>>8&255],"-").concat(e[r>>16&255]).concat(e[r>>24&255]).concat(e[255&s]).concat(e[s>>8&255]).concat(e[s>>16&255]).concat(e[s>>24&255])}}(),clamp:function(e,t,i){return Math.max(t,Math.min(i,e))},fmod:function(e,t){if(e1?1:i,Math.acos(i)},vec3FromMat4Scale:function(){var e=new X(3);return function(t,i){return e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=$.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=$.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=$.lenVec3(e),i}}(),vecToArray:function(){function e(e){return Math.round(1e5*e)/1e5}return function(t){for(var i=0,r=(t=Array.prototype.slice.call(t)).length;i0&&void 0!==arguments[0]?arguments[0]:new X(16);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e},identityMat3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new X(9);return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e},isIdentityMat4:function(e){return 1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15]},negateMat4:function(e,t){return t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t},addMat4:function(e,t,i){return i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i},addMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i},addScalarMat4:function(e,t,i){return $.addMat4Scalar(t,e,i)},subMat4:function(e,t,i){return i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i},subMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i},subScalarMat4:function(e,t,i){return i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i},mulMat4:function(e,t,i){i||(i=e);var r=e[0],s=e[1],n=e[2],o=e[3],a=e[4],l=e[5],u=e[6],A=e[7],c=e[8],h=e[9],d=e[10],p=e[11],f=e[12],v=e[13],g=e[14],m=e[15],_=t[0],y=t[1],b=t[2],w=t[3],B=t[4],x=t[5],P=t[6],C=t[7],M=t[8],E=t[9],F=t[10],k=t[11],I=t[12],D=t[13],S=t[14],T=t[15];return i[0]=_*r+y*a+b*c+w*f,i[1]=_*s+y*l+b*h+w*v,i[2]=_*n+y*u+b*d+w*g,i[3]=_*o+y*A+b*p+w*m,i[4]=B*r+x*a+P*c+C*f,i[5]=B*s+x*l+P*h+C*v,i[6]=B*n+x*u+P*d+C*g,i[7]=B*o+x*A+P*p+C*m,i[8]=M*r+E*a+F*c+k*f,i[9]=M*s+E*l+F*h+k*v,i[10]=M*n+E*u+F*d+k*g,i[11]=M*o+E*A+F*p+k*m,i[12]=I*r+D*a+S*c+T*f,i[13]=I*s+D*l+S*h+T*v,i[14]=I*n+D*u+S*d+T*g,i[15]=I*o+D*A+S*p+T*m,i},mulMat3:function(e,t,i){i||(i=new X(9));var r=e[0],s=e[3],n=e[6],o=e[1],a=e[4],l=e[7],u=e[2],A=e[5],c=e[8],h=t[0],d=t[3],p=t[6],f=t[1],v=t[4],g=t[7],m=t[2],_=t[5],y=t[8];return i[0]=r*h+s*f+n*m,i[3]=r*d+s*v+n*_,i[6]=r*p+s*g+n*y,i[1]=o*h+a*f+l*m,i[4]=o*d+a*v+l*_,i[7]=o*p+a*g+l*y,i[2]=u*h+A*f+c*m,i[5]=u*d+A*v+c*_,i[8]=u*p+A*g+c*y,i},mulMat4Scalar:function(e,t,i){return i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i},mulMat4v4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),r=t[0],s=t[1],n=t[2],o=t[3];return i[0]=e[0]*r+e[4]*s+e[8]*n+e[12]*o,i[1]=e[1]*r+e[5]*s+e[9]*n+e[13]*o,i[2]=e[2]*r+e[6]*s+e[10]*n+e[14]*o,i[3]=e[3]*r+e[7]*s+e[11]*n+e[15]*o,i},transposeMat4:function(e,t){var i=e[4],r=e[14],s=e[8],n=e[13],o=e[12],a=e[9];if(!t||e===t){var l=e[1],u=e[2],A=e[3],c=e[6],h=e[7],d=e[11];return e[1]=i,e[2]=s,e[3]=o,e[4]=l,e[6]=a,e[7]=n,e[8]=u,e[9]=c,e[11]=r,e[12]=A,e[13]=h,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=s,t[3]=o,t[4]=e[1],t[5]=e[5],t[6]=a,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=r,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3:function(e,t){if(t===e){var i=e[1],r=e[2],s=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=r,t[7]=s}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4:function(e){var t=e[0],i=e[1],r=e[2],s=e[3],n=e[4],o=e[5],a=e[6],l=e[7],u=e[8],A=e[9],c=e[10],h=e[11],d=e[12],p=e[13],f=e[14],v=e[15];return d*A*a*s-u*p*a*s-d*o*c*s+n*p*c*s+u*o*f*s-n*A*f*s-d*A*r*l+u*p*r*l+d*i*c*l-t*p*c*l-u*i*f*l+t*A*f*l+d*o*r*h-n*p*r*h-d*i*a*h+t*p*a*h+n*i*f*h-t*o*f*h-u*o*r*v+n*A*r*v+u*i*a*v-t*A*a*v-n*i*c*v+t*o*c*v},inverseMat4:function(e,t){t||(t=e);var i=e[0],r=e[1],s=e[2],n=e[3],o=e[4],a=e[5],l=e[6],u=e[7],A=e[8],c=e[9],h=e[10],d=e[11],p=e[12],f=e[13],v=e[14],g=e[15],m=i*a-r*o,_=i*l-s*o,y=i*u-n*o,b=r*l-s*a,w=r*u-n*a,B=s*u-n*l,x=A*f-c*p,P=A*v-h*p,C=A*g-d*p,M=c*v-h*f,E=c*g-d*f,F=h*g-d*v,k=1/(m*F-_*E+y*M+b*C-w*P+B*x);return t[0]=(a*F-l*E+u*M)*k,t[1]=(-r*F+s*E-n*M)*k,t[2]=(f*B-v*w+g*b)*k,t[3]=(-c*B+h*w-d*b)*k,t[4]=(-o*F+l*C-u*P)*k,t[5]=(i*F-s*C+n*P)*k,t[6]=(-p*B+v*y-g*_)*k,t[7]=(A*B-h*y+d*_)*k,t[8]=(o*E-a*C+u*x)*k,t[9]=(-i*E+r*C-n*x)*k,t[10]=(p*w-f*y+g*m)*k,t[11]=(-A*w+c*y-d*m)*k,t[12]=(-o*M+a*P-l*x)*k,t[13]=(i*M-r*P+s*x)*k,t[14]=(-p*b+f*_-v*m)*k,t[15]=(A*b-c*_+h*m)*k,t},traceMat4:function(e){return e[0]+e[5]+e[10]+e[15]},translationMat4v:function(e,t){var i=t||$.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v:function(e,t){var i=t||$.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(O=new X(3),function(e,t,i,r){return O[0]=e,O[1]=t,O[2]=i,$.translationMat4v(O,r)}),translationMat4s:function(e,t){return $.translationMat4c(e,e,e,t)},translateMat4v:function(e,t){return $.translateMat4c(e[0],e[1],e[2],t)},translateMat4c:function(e,t,i,r){var s=r[3];r[0]+=s*e,r[1]+=s*t,r[2]+=s*i;var n=r[7];r[4]+=n*e,r[5]+=n*t,r[6]+=n*i;var o=r[11];r[8]+=o*e,r[9]+=o*t,r[10]+=o*i;var a=r[15];return r[12]+=a*e,r[13]+=a*t,r[14]+=a*i,r},setMat4Translation:function(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i},rotationMat4v:function(e,t,i){var r,s,n,o,a,l,u=$.normalizeVec4([t[0],t[1],t[2],0],[]),A=Math.sin(e),c=Math.cos(e),h=1-c,d=u[0],p=u[1],f=u[2];return r=d*p,s=p*f,n=f*d,o=d*A,a=p*A,l=f*A,(i=i||$.mat4())[0]=h*d*d+c,i[1]=h*r+l,i[2]=h*n-a,i[3]=0,i[4]=h*r-l,i[5]=h*p*p+c,i[6]=h*s+o,i[7]=0,i[8]=h*n+a,i[9]=h*s-o,i[10]=h*f*f+c,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:function(e,t,i,r,s){return $.rotationMat4v(e,[t,i,r],s)},scalingMat4v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat4();return t[0]=e[0],t[5]=e[1],t[10]=e[2],t},scalingMat3v:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.identityMat3();return t[0]=e[0],t[4]=e[1],t},scalingMat4c:function(){var e=new X(3);return function(t,i,r,s){return e[0]=t,e[1]=i,e[2]=r,$.scalingMat4v(e,s)}}(),scaleMat4c:function(e,t,i,r){return r[0]*=e,r[4]*=t,r[8]*=i,r[1]*=e,r[5]*=t,r[9]*=i,r[2]*=e,r[6]*=t,r[10]*=i,r[3]*=e,r[7]*=t,r[11]*=i,r},scaleMat4v:function(e,t){var i=e[0],r=e[1],s=e[2];return t[0]*=i,t[4]*=r,t[8]*=s,t[1]*=i,t[5]*=r,t[9]*=s,t[2]*=i,t[6]*=r,t[10]*=s,t[3]*=i,t[7]*=r,t[11]*=s,t},scalingMat4s:function(e){return $.scalingMat4c(e,e,e)},rotationTranslationMat4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.mat4(),r=e[0],s=e[1],n=e[2],o=e[3],a=r+r,l=s+s,u=n+n,A=r*a,c=r*l,h=r*u,d=s*l,p=s*u,f=n*u,v=o*a,g=o*l,m=o*u;return i[0]=1-(d+f),i[1]=c+m,i[2]=h-g,i[3]=0,i[4]=c-m,i[5]=1-(A+f),i[6]=p+v,i[7]=0,i[8]=h+g,i[9]=p-v,i[10]=1-(A+d),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),r=$.clamp,s=e[0],n=e[4],o=e[8],a=e[1],l=e[5],u=e[9],A=e[2],c=e[6],h=e[10];return"XYZ"===t?(i[1]=Math.asin(r(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-u,h),i[2]=Math.atan2(-n,s)):(i[0]=Math.atan2(c,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-r(u,-1,1)),Math.abs(u)<.99999?(i[1]=Math.atan2(o,h),i[2]=Math.atan2(a,l)):(i[1]=Math.atan2(-A,s),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(r(c,-1,1)),Math.abs(c)<.99999?(i[1]=Math.atan2(-A,h),i[2]=Math.atan2(-n,l)):(i[1]=0,i[2]=Math.atan2(a,s))):"ZYX"===t?(i[1]=Math.asin(-r(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(c,h),i[2]=Math.atan2(a,s)):(i[0]=0,i[2]=Math.atan2(-n,l))):"YZX"===t?(i[2]=Math.asin(r(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-u,l),i[1]=Math.atan2(-A,s)):(i[0]=0,i[1]=Math.atan2(o,h))):"XZY"===t&&(i[2]=Math.asin(-r(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(c,l),i[1]=Math.atan2(o,s)):(i[0]=Math.atan2(-u,h),i[1]=0)),i},composeMat4:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.mat4();return $.quaternionToRotationMat4(t,r),$.scaleMat4v(i,r),$.translateMat4v(e,r),r},decomposeMat4:function(){var e=new X(3),t=new X(16);return function(i,r,s,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];var o=$.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];var a=$.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];var l=$.lenVec3(e);$.determinantMat4(i)<0&&(o=-o),r[0]=i[12],r[1]=i[13],r[2]=i[14],t.set(i);var u=1/o,A=1/a,c=1/l;return t[0]*=u,t[1]*=u,t[2]*=u,t[4]*=A,t[5]*=A,t[6]*=A,t[8]*=c,t[9]*=c,t[10]*=c,$.mat4ToQuaternion(t,s),n[0]=o,n[1]=a,n[2]=l,this}}(),getColMat4:function(e,t){var i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4:function(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v:function(e,t,i,r){r||(r=$.mat4());var s,n,o,a,l,u,A,c,h,d,p=e[0],f=e[1],v=e[2],g=i[0],m=i[1],_=i[2],y=t[0],b=t[1],w=t[2];return p===y&&f===b&&v===w?$.identityMat4():(s=p-y,n=f-b,o=v-w,a=m*(o*=d=1/Math.sqrt(s*s+n*n+o*o))-_*(n*=d),l=_*(s*=d)-g*o,u=g*n-m*s,(d=Math.sqrt(a*a+l*l+u*u))?(a*=d=1/d,l*=d,u*=d):(a=0,l=0,u=0),A=n*u-o*l,c=o*a-s*u,h=s*l-n*a,(d=Math.sqrt(A*A+c*c+h*h))?(A*=d=1/d,c*=d,h*=d):(A=0,c=0,h=0),r[0]=a,r[1]=A,r[2]=s,r[3]=0,r[4]=l,r[5]=c,r[6]=n,r[7]=0,r[8]=u,r[9]=h,r[10]=o,r[11]=0,r[12]=-(a*p+l*f+u*v),r[13]=-(A*p+c*f+h*v),r[14]=-(s*p+n*f+o*v),r[15]=1,r)},lookAtMat4c:function(e,t,i,r,s,n,o,a,l){return $.lookAtMat4v([e,t,i],[r,s,n],[o,a,l],[])},orthoMat4c:function(e,t,i,r,s,n,o){o||(o=$.mat4());var a=t-e,l=r-i,u=n-s;return o[0]=2/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2/l,o[6]=0,o[7]=0,o[8]=0,o[9]=0,o[10]=-2/u,o[11]=0,o[12]=-(e+t)/a,o[13]=-(r+i)/l,o[14]=-(n+s)/u,o[15]=1,o},frustumMat4v:function(e,t,i){i||(i=$.mat4());var r=[e[0],e[1],e[2],0],s=[t[0],t[1],t[2],0];$.addVec4(s,r,J),$.subVec4(s,r,Z);var n=2*r[2],o=Z[0],a=Z[1],l=Z[2];return i[0]=n/o,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/a,i[6]=0,i[7]=0,i[8]=J[0]/o,i[9]=J[1]/a,i[10]=-J[2]/l,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*s[2]/l,i[15]=0,i},frustumMat4:function(e,t,i,r,s,n,o){o||(o=$.mat4());var a=t-e,l=r-i,u=n-s;return o[0]=2*s/a,o[1]=0,o[2]=0,o[3]=0,o[4]=0,o[5]=2*s/l,o[6]=0,o[7]=0,o[8]=(t+e)/a,o[9]=(r+i)/l,o[10]=-(n+s)/u,o[11]=-1,o[12]=0,o[13]=0,o[14]=-n*s*2/u,o[15]=0,o},perspectiveMat4:function(e,t,i,r,s){var n=[],o=[];return n[2]=i,o[2]=r,o[1]=n[2]*Math.tan(e/2),n[1]=-o[1],o[0]=o[1]*t,n[0]=-o[0],$.frustumMat4v(n,o,s)},compareMat4:function(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15]},transformPoint3:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),r=t[0],s=t[1],n=t[2];return i[0]=e[0]*r+e[4]*s+e[8]*n+e[12],i[1]=e[1]*r+e[5]*s+e[9]*n+e[13],i[2]=e[2]*r+e[6]*s+e[10]*n+e[14],i},transformPoint4:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4();return i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i},transformPoints3:function(e,t,i){for(var r,s,n,o,a,l=i||[],u=t.length,A=e[0],c=e[1],h=e[2],d=e[3],p=e[4],f=e[5],v=e[6],g=e[7],m=e[8],_=e[9],y=e[10],b=e[11],w=e[12],B=e[13],x=e[14],P=e[15],C=0;C2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2];e[3];var c=e[4],h=e[5],d=e[6];e[7];var p=e[8],f=e[9],v=e[10];e[11];var g=e[12],m=e[13],_=e[14];for(e[15],i=0;i2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;i3&&void 0!==arguments[3]?arguments[3]:e,s=Math.cos(i),n=Math.sin(i),o=e[0]-t[0],a=e[1]-t[1];return r[0]=o*s-a*n+t[0],r[1]=o*n+a*s+t[1],e},rotateVec3X:function(e,t,i,r){var s=[],n=[];return s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],n[0]=s[0],n[1]=s[1]*Math.cos(i)-s[2]*Math.sin(i),n[2]=s[1]*Math.sin(i)+s[2]*Math.cos(i),r[0]=n[0]+t[0],r[1]=n[1]+t[1],r[2]=n[2]+t[2],r},rotateVec3Y:function(e,t,i,r){var s=[],n=[];return s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],n[0]=s[2]*Math.sin(i)+s[0]*Math.cos(i),n[1]=s[1],n[2]=s[2]*Math.cos(i)-s[0]*Math.sin(i),r[0]=n[0]+t[0],r[1]=n[1]+t[1],r[2]=n[2]+t[2],r},rotateVec3Z:function(e,t,i,r){var s=[],n=[];return s[0]=e[0]-t[0],s[1]=e[1]-t[1],s[2]=e[2]-t[2],n[0]=s[0]*Math.cos(i)-s[1]*Math.sin(i),n[1]=s[0]*Math.sin(i)+s[1]*Math.cos(i),n[2]=s[2],r[0]=n[0]+t[0],r[1]=n[1]+t[1],r[2]=n[2]+t[2],r},projectVec4:function(e,t){var i=1/e[3];return(t=t||$.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(L=new X(16),R=new X(16),U=new X(16),function(e,t,i,r){return this.transformVec3(this.mulMat4(this.inverseMat4(t,L),this.inverseMat4(i,R),U),e,r)}),lerpVec3:function(e,t,i,r,s,n){var o=n||$.vec3(),a=(e-t)/(i-t);return o[0]=r[0]+a*(s[0]-r[0]),o[1]=r[1]+a*(s[1]-r[1]),o[2]=r[2]+a*(s[2]-r[2]),o},lerpMat4:function(e,t,i,r,s,n){var o=n||$.mat4(),a=(e-t)/(i-t);return o[0]=r[0]+a*(s[0]-r[0]),o[1]=r[1]+a*(s[1]-r[1]),o[2]=r[2]+a*(s[2]-r[2]),o[3]=r[3]+a*(s[3]-r[3]),o[4]=r[4]+a*(s[4]-r[4]),o[5]=r[5]+a*(s[5]-r[5]),o[6]=r[6]+a*(s[6]-r[6]),o[7]=r[7]+a*(s[7]-r[7]),o[8]=r[8]+a*(s[8]-r[8]),o[9]=r[9]+a*(s[9]-r[9]),o[10]=r[10]+a*(s[10]-r[10]),o[11]=r[11]+a*(s[11]-r[11]),o[12]=r[12]+a*(s[12]-r[12]),o[13]=r[13]+a*(s[13]-r[13]),o[14]=r[14]+a*(s[14]-r[14]),o[15]=r[15]+a*(s[15]-r[15]),o},flatten:function(e){var t,i,r,s,n,o=[];for(t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:$.vec4();return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e},eulerToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),r=e[0]*$.DEGTORAD/2,s=e[1]*$.DEGTORAD/2,n=e[2]*$.DEGTORAD/2,o=Math.cos(r),a=Math.cos(s),l=Math.cos(n),u=Math.sin(r),A=Math.sin(s),c=Math.sin(n);return"XYZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"YXZ"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"ZXY"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l-u*A*c):"ZYX"===t?(i[0]=u*a*l-o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l+u*A*c):"YZX"===t?(i[0]=u*a*l+o*A*c,i[1]=o*A*l+u*a*c,i[2]=o*a*c-u*A*l,i[3]=o*a*l-u*A*c):"XZY"===t&&(i[0]=u*a*l-o*A*c,i[1]=o*A*l-u*a*c,i[2]=o*a*c+u*A*l,i[3]=o*a*l+u*A*c),i},mat4ToQuaternion:function(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),r=e[0],s=e[4],n=e[8],o=e[1],a=e[5],l=e[9],u=e[2],A=e[6],c=e[10],h=r+a+c;return h>0?(t=.5/Math.sqrt(h+1),i[3]=.25/t,i[0]=(A-l)*t,i[1]=(n-u)*t,i[2]=(o-s)*t):r>a&&r>c?(t=2*Math.sqrt(1+r-a-c),i[3]=(A-l)/t,i[0]=.25*t,i[1]=(s+o)/t,i[2]=(n+u)/t):a>c?(t=2*Math.sqrt(1+a-r-c),i[3]=(n-u)/t,i[0]=(s+o)/t,i[1]=.25*t,i[2]=(l+A)/t):(t=2*Math.sqrt(1+c-r-a),i[3]=(o-s)/t,i[0]=(n+u)/t,i[1]=(l+A)/t,i[2]=.25*t),i},vec3PairToQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),r=Math.sqrt($.dotVec3(e,e)*$.dotVec3(t,t)),s=r+$.dotVec3(e,t);return s<1e-8*r?(s=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):$.cross3Vec3(e,t,i),i[3]=s,$.normalizeQuaternion(i)},angleAxisToQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=e[3]/2,r=Math.sin(i);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(i),t},quaternionToEuler:function(){var e=new X(16);return function(t,i,r){return r=r||$.vec3(),$.quaternionToRotationMat4(t,e),$.mat4ToEuler(e,i,r),r}}(),mulQuaternions:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec4(),r=e[0],s=e[1],n=e[2],o=e[3],a=t[0],l=t[1],u=t[2],A=t[3];return i[0]=o*a+r*A+s*u-n*l,i[1]=o*l+s*A+n*a-r*u,i[2]=o*u+n*A+r*l-s*a,i[3]=o*A-r*a-s*l-n*u,i},vec3ApplyQuaternion:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:$.vec3(),r=t[0],s=t[1],n=t[2],o=e[0],a=e[1],l=e[2],u=e[3],A=u*r+a*n-l*s,c=u*s+l*r-o*n,h=u*n+o*s-a*r,d=-o*r-a*s-l*n;return i[0]=A*u+d*-o+c*-l-h*-a,i[1]=c*u+d*-a+h*-o-A*-l,i[2]=h*u+d*-l+A*-a-c*-o,i},quaternionToMat4:function(e,t){t=$.identityMat4(t);var i=e[0],r=e[1],s=e[2],n=e[3],o=2*i,a=2*r,l=2*s,u=o*n,A=a*n,c=l*n,h=o*i,d=a*i,p=l*i,f=a*r,v=l*r,g=l*s;return t[0]=1-(f+g),t[1]=d+c,t[2]=p-A,t[4]=d-c,t[5]=1-(h+g),t[6]=v+u,t[8]=p+A,t[9]=v-u,t[10]=1-(h+f),t},quaternionToRotationMat4:function(e,t){var i=e[0],r=e[1],s=e[2],n=e[3],o=i+i,a=r+r,l=s+s,u=i*o,A=i*a,c=i*l,h=r*a,d=r*l,p=s*l,f=n*o,v=n*a,g=n*l;return t[0]=1-(h+p),t[4]=A-g,t[8]=c+v,t[1]=A+g,t[5]=1-(u+p),t[9]=d-f,t[2]=c-v,t[6]=d+f,t[10]=1-(u+h),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e,i=$.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:e;return t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t},inverseQuaternion:function(e,t){return $.normalizeQuaternion($.conjugateQuaternion(e,t))},quaternionToAngleAxis:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec4(),i=(e=$.normalizeQuaternion(e,q))[3],r=2*Math.acos(i),s=Math.sqrt(1-i*i);return s<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/s,t[1]=e[1]/s,t[2]=e[2]/s),t[3]=r,t},AABB3:function(e){return new X(e||6)},AABB2:function(e){return new X(e||4)},OBB3:function(e){return new X(e||32)},OBB2:function(e){return new X(e||16)},Sphere3:function(e,t,i,r){return new X([e,t,i,r])},transformOBB3:function(e,t){var i,r,s,n,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:t,a=t.length,l=e[0],u=e[1],A=e[2],c=e[3],h=e[4],d=e[5],p=e[6],f=e[7],v=e[8],g=e[9],m=e[10],_=e[11],y=e[12],b=e[13],w=e[14],B=e[15];for(i=0;ia?o:a,n[1]+=l>u?l:u,n[2]+=A>c?A:c,Math.abs($.lenVec3(n))}}(),getAABB3Area:function(e){return(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2])},getAABB3Center:function(e,t){var i=t||$.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center:function(e,t){var i=t||$.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:$.AABB3();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MAX_DOUBLE,e[3]=$.MIN_DOUBLE,e[4]=$.MIN_DOUBLE,e[5]=$.MIN_DOUBLE,e},AABB3ToOBB3:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.OBB3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t},positions3ToAABB3:function(){var e=new X(3);return function(t,i,r){i=i||$.AABB3();for(var s,n,o,a=$.MAX_DOUBLE,l=$.MAX_DOUBLE,u=$.MAX_DOUBLE,A=$.MIN_DOUBLE,c=$.MIN_DOUBLE,h=$.MIN_DOUBLE,d=0,p=t.length;dA&&(A=s),n>c&&(c=n),o>h&&(h=o);return i[0]=a,i[1]=l,i[2]=u,i[3]=A,i[4]=c,i[5]=h,i}}(),OBB3ToAABB3:function(e){for(var t,i,r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),r>A&&(A=r);return s[0]=n,s[1]=o,s[2]=a,s[3]=l,s[4]=u,s[5]=A,s},points3ToAABB3:function(e){for(var t,i,r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB3(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MAX_DOUBLE,l=$.MIN_DOUBLE,u=$.MIN_DOUBLE,A=$.MIN_DOUBLE,c=0,h=e.length;cl&&(l=t),i>u&&(u=i),r>A&&(A=r);return s[0]=n,s[1]=o,s[2]=a,s[3]=l,s[4]=u,s[5]=A,s},points3ToSphere3:function(){var e=new X(3);return function(t,i){i=i||$.vec4();var r,s=0,n=0,o=0,a=t.length;for(r=0;ru&&(u=l);return i[3]=u,i}}(),positions3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,r){r=r||$.vec4();var s,n=0,o=0,a=0,l=i.length,u=0;for(s=0;su&&(u=A);return r[3]=u,r}}(),OBB3ToSphere3:function(){var e=new X(3),t=new X(3);return function(i,r){r=r||$.vec4();var s,n=0,o=0,a=0,l=i.length,u=l/4;for(s=0;sc&&(c=A);return r[3]=c,r}}(),getSphere3Center:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3();return t[0]=e[0],t[1]=e[1],t[2]=e[2],t},getPositionsCenter:function(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(),i=0,r=0,s=0,n=0,o=e.length;nt[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]i&&(e[0]=i),e[1]>r&&(e[1]=r),e[2]>s&&(e[2]=s),e[3]0&&void 0!==arguments[0]?arguments[0]:$.AABB2();return e[0]=$.MAX_DOUBLE,e[1]=$.MAX_DOUBLE,e[2]=$.MIN_DOUBLE,e[3]=$.MIN_DOUBLE,e},point3AABB3Intersect:function(e,t){return e[0]>t[0]||e[3]t[1]||e[4]t[2]||e[5]0?(r=e[0]*i[0],s=e[0]*i[3]):(r=e[0]*i[3],s=e[0]*i[0]),e[1]>0?(r+=e[1]*i[1],s+=e[1]*i[4]):(r+=e[1]*i[4],s+=e[1]*i[1]),e[2]>0?(r+=e[2]*i[2],s+=e[2]*i[5]):(r+=e[2]*i[5],s+=e[2]*i[2]),r<=-t&&s<=-t?-1:r>=-t&&s>=-t?1:0},OBB3ToAABB2:function(e){for(var t,i,r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.AABB2(),n=$.MAX_DOUBLE,o=$.MAX_DOUBLE,a=$.MIN_DOUBLE,l=$.MIN_DOUBLE,u=0,A=e.length;ua&&(a=t),i>l&&(l=i);return s[0]=n,s[1]=o,s[2]=a,s[3]=l,s},expandAABB2:function(e,t){return e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]3&&void 0!==arguments[3]?arguments[3]:e,s=.5*(e[0]+1),n=.5*(e[1]+1),o=.5*(e[2]+1),a=.5*(e[3]+1);return r[0]=Math.floor(s*t),r[1]=i-Math.floor(a*i),r[2]=Math.floor(o*t),r[3]=i-Math.floor(n*i),r},tangentQuadraticBezier:function(e,t,i,r){return 2*(1-e)*(i-t)+2*e*(r-i)},tangentQuadraticBezier3:function(e,t,i,r,s){return-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*r*(1-e)-3*e*e*r+3*e*e*s},tangentSpline:function(e){return 6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e)},catmullRomInterpolate:function(e,t,i,r,s){var n=.5*(i-e),o=.5*(r-t),a=s*s;return(2*t-2*i+n+o)*(s*a)+(-3*t+3*i-2*n-o)*a+n*s+t},b2p0:function(e,t){var i=1-e;return i*i*t},b2p1:function(e,t){return 2*(1-e)*e*t},b2p2:function(e,t){return e*e*t},b2:function(e,t,i,r){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,r)},b3p0:function(e,t){var i=1-e;return i*i*i*t},b3p1:function(e,t){var i=1-e;return 3*i*i*e*t},b3p2:function(e,t){return 3*(1-e)*e*e*t},b3p3:function(e,t){return e*e*e*t},b3:function(e,t,i,r,s){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,r)+this.b3p3(e,s)},triangleNormal:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:$.vec3(),s=t[0]-e[0],n=t[1]-e[1],o=t[2]-e[2],a=i[0]-e[0],l=i[1]-e[1],u=i[2]-e[2],A=n*u-o*l,c=o*a-s*u,h=s*l-n*a,d=Math.sqrt(A*A+c*c+h*h);return 0===d?(r[0]=0,r[1]=0,r[2]=0):(r[0]=A/d,r[1]=c/d,r[2]=h/d),r},rayTriangleIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),r=new X(3),s=new X(3);return function(n,o,a,l,u,A){A=A||$.vec3();var c=$.subVec3(l,a,e),h=$.subVec3(u,a,t),d=$.cross3Vec3(o,h,i),p=$.dotVec3(c,d);if(p<1e-6)return null;var f=$.subVec3(n,a,r),v=$.dotVec3(f,d);if(v<0||v>p)return null;var g=$.cross3Vec3(f,c,s),m=$.dotVec3(o,g);if(m<0||v+m>p)return null;var _=$.dotVec3(h,g)/p;return A[0]=n[0]+_*o[0],A[1]=n[1]+_*o[1],A[2]=n[2]+_*o[2],A}}(),rayPlaneIntersect:function(){var e=new X(3),t=new X(3),i=new X(3),r=new X(3);return function(s,n,o,a,l,u){u=u||$.vec3(),n=$.normalizeVec3(n,e);var A=$.subVec3(a,o,t),c=$.subVec3(l,o,i),h=$.cross3Vec3(A,c,r);$.normalizeVec3(h,h);var d=-$.dotVec3(o,h),p=-($.dotVec3(s,h)+d)/$.dotVec3(n,h);return u[0]=s[0]+p*n[0],u[1]=s[1]+p*n[1],u[2]=s[2]+p*n[2],u}}(),cartesianToBarycentric:function(){var e=new X(3),t=new X(3),i=new X(3);return function(r,s,n,o,a){var l=$.subVec3(o,s,e),u=$.subVec3(n,s,t),A=$.subVec3(r,s,i),c=$.dotVec3(l,l),h=$.dotVec3(l,u),d=$.dotVec3(l,A),p=$.dotVec3(u,u),f=$.dotVec3(u,A),v=c*p-h*h;if(0===v)return null;var g=1/v,m=(p*d-h*f)*g,_=(c*f-h*d)*g;return a[0]=1-m-_,a[1]=_,a[2]=m,a}}(),barycentricInsideTriangle:function(e){var t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian:function(e,t,i,r){var s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:$.vec3(),n=e[0],o=e[1],a=e[2];return s[0]=t[0]*n+i[0]*o+r[0]*a,s[1]=t[1]*n+i[1]*o+r[1]*a,s[2]=t[2]*n+i[2]*o+r[2]*a,s},mergeVertices:function(e,t,i,r){var s,n,o,a,l,u,A={},c=[],h=[],d=t?[]:null,p=i?[]:null,f=[],v=Math.pow(10,4),g=0;for(l=0,u=e.length;l>24&255,o=c>>16&255,n=c>>8&255,s=255&c,r=3*t[p],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],A[d++]=s,A[d++]=n,A[d++]=o,A[d++]=a,r=3*t[p+1],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],A[d++]=s,A[d++]=n,A[d++]=o,A[d++]=a,r=3*t[p+2],u[h++]=e[r],u[h++]=e[r+1],u[h++]=e[r+2],A[d++]=s,A[d++]=n,A[d++]=o,A[d++]=a,c++;return{positions:u,colors:A}},faceToVertexNormals:function(e,t){var i,r,s,n,o,a,l,u,A,c,h,d=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},p=d.smoothNormalsAngleThreshold||20,f={},v=[],g={},m=4,_=Math.pow(10,m);for(l=0,A=e.length;ll[3]&&(l[3]=s[h]),s[h+1]l[4]&&(l[4]=s[h+1]),s[h+2]l[5]&&(l[5]=s[h+2])}if(i.length<20||n>10)return u.triangles=i,u.leaf=!0,u;e[0]=l[3]-l[0],e[1]=l[4]-l[1],e[2]=l[5]-l[2];var d=0;e[1]>e[d]&&(d=1),e[2]>e[d]&&(d=2),u.splitDim=d;var p=(l[d]+l[d+3])/2,f=new Array(i.length),v=0,g=new Array(i.length),m=0;for(o=0,a=i.length;o2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,s=e.length;r2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,s=e.length;r=0?1:-1),r=(1-Math.abs(i))*(r>=0?1:-1));var n=Math.sqrt(i*i+r*r+s*s);return t[0]=i/n,t[1]=r/n,t[2]=s/n,t},octDecodeVec2s:function(e,t){for(var i=0,r=0,s=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[r+0]=n/l,t[r+1]=o/l,t[r+2]=a/l,r+=3}return t}};$.buildEdgeIndices=function(){var e=[],t=[],i=[],r=[],s=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(s,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=s.length;AI)||(E=i[P.index1],F=i[P.index2],(!S&&E>65535||F>65535)&&(S=!0),k.push(E),k.push(F));return S?new Uint32Array(k):new Uint16Array(k)}}(),$.planeClipsPositions3=function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:3,s=0,n=i.length;s=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&$.containsAABB3(e.left.aabb,r))this._insertEntity(e.left,t,i+1);else if(e.right&&$.containsAABB3(e.right.aabb,r))this._insertEntity(e.right,t,i+1);else{var s=e.aabb;ee[0]=s[3]-s[0],ee[1]=s[4]-s[1],ee[2]=s[5]-s[2];var n=0;if(ee[1]>ee[n]&&(n=1),ee[2]>ee[n]&&(n=2),!e.left){var o=s.slice();if(o[n+3]=(s[n]+s[n+3])/2,e.left={aabb:o},$.containsAABB3(o,r))return void this._insertEntity(e.left,t,i+1)}if(!e.right){var a=s.slice();if(a[n]=(s[n]+s[n+3])/2,e.right={aabb:a},$.containsAABB3(a,r))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}}},{key:"destroy",value:function(){var e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}]),e}(),ie=function(){function e(){x(this,e),this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}return C(e,[{key:"length",get:function(){return this._length}},{key:"shift",value:function(){if(this._index>=this._headLength){var e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}var t=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,t}},{key:"push",value:function(e){return this._length++,this._tail.push(e),this}},{key:"unshift",value:function(e){return this._head[--this._index]=e,this._length++,this}}]),e}(),re={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var se=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),r=i+e[1],s=i;s1&&void 0!==arguments[1]?arguments[1]:null;ce.push(e),ce.push(t)},this.runTasks=function(){for(var e,t,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,r=(new Date).getTime(),s=0;ce.length>0&&(i<0||r0&&ae>0){var t=1e3/ae;fe+=t,de.push(t),de.length>=30&&(fe-=de.shift()),re.frame.fps=Math.round(fe/de.length)}for(var i in _e.scenes)_e.scenes[i].compile();be(e),pe=e};ve=function(){ye()},ge=100,me=Date.now()+ge,function e(){var t=Date.now()-me;ve(),me+=ge,setTimeout(e,Math.max(0,ge-t))}();function be(e){var t=_e.runTasks(e+10),i=_e.getNumTasks();re.frame.tasksRun=t,re.frame.tasksScheduled=i,re.frame.tasksBudget=10}!function e(){var t=Date.now();if(ae=t-pe,pe>0&&ae>0){var i=1e3/ae;fe+=i,de.push(i),de.length>=30&&(fe-=de.shift()),re.frame.fps=Math.round(fe/de.length)}be(t),function(e){for(var t in he.time=e,_e.scenes)if(_e.scenes.hasOwnProperty(t)){var i=_e.scenes[t];he.sceneId=t,he.startTime=i.startTime,he.deltaTime=null!=he.prevTime?he.time-he.prevTime:0,i.fire("tick",he,!0)}he.prevTime=e}(t),function(){var e,t,i,r,s,n=_e.scenes,o=!1;for(s in n)n.hasOwnProperty(s)&&(e=n[s],(t=ue[s])||(t=ue[s]={}),i=e.ticksPerOcclusionTest,t.ticksPerOcclusionTest!==i&&(t.ticksPerOcclusionTest=i,t.renderCountdown=i),--e.occlusionTestCountdown<=0&&(e.doOcclusionTest(),e.occlusionTestCountdown=i),r=e.ticksPerRender,t.ticksPerRender!==r&&(t.ticksPerRender=r,t.renderCountdown=r),0==--t.renderCountdown&&(e.render(o),t.renderCountdown=r))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(ye):requestAnimationFrame(e)}();var we=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,e),this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=i.viewer;else{if("Scene"===t.type)this.scene=t;else{if(!(t instanceof e))throw"Invalid param: owner must be a Component";this.scene=t.scene}this._owner=t}this._dontClear=!!i.dontClear,this._renderer=this.scene._renderer,this.meta=i.meta||{},this.id=i.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,t&&t._own(this)}return C(e,[{key:"type",get:function(){return"Component"}},{key:"isComponent",get:function(){return!0}},{key:"glRedraw",value:function(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}},{key:"glResort",value:function(){this._renderer&&this._renderer.needStateSort()}},{key:"owner",get:function(){return this._owner}},{key:"isType",value:function(e){return this.type===e}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var r,s=this._eventSubs[e];if(s)for(var n in s)s.hasOwnProperty(n)&&(r=s[n],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var s=this._subIdMap.addItem();r[s]={callback:t,scope:i||this},this._subIdEvents[s]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),s}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var r=this,s=this.on(e,(function(e){r.off(s),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}},{key:"_message",value:function(e){return" ["+this.type+" "+le.inQuotes(this.id)+"]: "+e}},{key:"warn",value:function(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}},{key:"error",value:function(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}},{key:"_attach",value:function(e){var t=e.name;if(t){var i=e.component,r=e.sceneDefault,s=e.sceneSingleton,n=e.type,o=e.on,a=!1!==e.recompiles;if(i&&(le.isNumeric(i)||le.isString(i))){var l=i;if(!(i=this.scene.components[l]))return void this.error("Component not found: "+le.inQuotes(l))}if(!i)if(!0===s){var u=this.scene.types[n];for(var A in u)if(u.hasOwnProperty){i=u[A];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===r&&!(i=this.scene[t]))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+le.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+le.inQuotes(i.id))}this._attachments||(this._attachments={});var c,h,d,p=this._attached[t];if(p){if(i&&p.id===i.id)return;var f=this._attachments[p.id];for(h=0,d=(c=f.subs).length;h=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}]),e}(),Me=C((function e(){x(this,e),this.planes=[new Ce,new Ce,new Ce,new Ce,new Ce,new Ce]}));function Ee(e,t,i){var r=$.mulMat4(i,t,Pe),s=r[0],n=r[1],o=r[2],a=r[3],l=r[4],u=r[5],A=r[6],c=r[7],h=r[8],d=r[9],p=r[10],f=r[11],v=r[12],g=r[13],m=r[14],_=r[15];e.planes[0].set(a-s,c-l,f-h,_-v),e.planes[1].set(a+s,c+l,f+h,_+v),e.planes[2].set(a-n,c-u,f-d,_-g),e.planes[3].set(a+n,c+u,f+d,_+g),e.planes[4].set(a-o,c-A,f-p,_-m),e.planes[5].set(a+o,c+A,f+p,_+m)}function Fe(e,t){var i=Me.INSIDE,r=Be,s=xe;r[0]=t[0],r[1]=t[1],r[2]=t[2],s[0]=t[3],s[1]=t[4],s[2]=t[5];for(var n=[r,s],o=0;o<6;++o){var a=e.planes[o];if(a.normal[0]*n[a.testVertex[0]][0]+a.normal[1]*n[a.testVertex[1]][1]+a.normal[2]*n[a.testVertex[2]][2]+a.offset<0)return Me.OUTSIDE;a.normal[0]*n[1-a.testVertex[0]][0]+a.normal[1]*n[1-a.testVertex[1]][1]+a.normal[2]*n[1-a.testVertex[2]][2]+a.offset<0&&(i=Me.INTERSECT)}return i}Me.INSIDE=0,Me.INTERSECT=1,Me.OUTSIDE=2;var ke=function(e){g(i,we);var t=_(i);function i(){var e,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(x(this,i),!r.viewer)throw"[MarqueePicker] Missing config: viewer";if(!r.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";return(e=t.call(this,r.viewer.scene,r)).viewer=r.viewer,e._objectsKdTree3=r.objectsKdTree3,e._canvasMarqueeCorner1=$.vec2(),e._canvasMarqueeCorner2=$.vec2(),e._canvasMarquee=$.AABB2(),e._marqueeFrustum=new Me,e._marqueeFrustumProjMat=$.mat4(),e._pickMode=!1,e._marqueeElement=document.createElement("div"),document.body.appendChild(e._marqueeElement),e._marqueeElement.style.position="absolute",e._marqueeElement.style["z-index"]="40000005",e._marqueeElement.style.width="8px",e._marqueeElement.style.height="8px",e._marqueeElement.style.visibility="hidden",e._marqueeElement.style.top="0px",e._marqueeElement.style.left="0px",e._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",e._marqueeElement.style.opacity=1,e._marqueeElement.style["pointer-events"]="none",e}return C(i,[{key:"setMarqueeCorner1",value:function(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarqueeCorner2",value:function(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}},{key:"setMarquee",value:function(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}},{key:"setMarqueeVisible",value:function(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}},{key:"getMarqueeVisible",value:function(){return this._marqueVisible}},{key:"setPickMode",value:function(e){if(e!==i.PICK_MODE_INSIDE&&e!==i.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===i.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}},{key:"getPickMode",value:function(){return this._pickMode}},{key:"clear",value:function(){this.fire("clear",{})}},{key:"pick",value:function(){var e=this;this._updateMarquee(),this._buildMarqueeFrustum();var t=[];return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&function r(s){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(n===Me.INTERSECT&&(n=Fe(e._marqueeFrustum,s.aabb)),n!==Me.OUTSIDE){if(s.entities)for(var o=s.entities,a=0,l=o.length;a3||i>3)&&c.pick()}})),document.addEventListener("mouseup",(function(e){r.getActive()&&0===e.button&&(clearTimeout(A),d&&(c.setMarqueeVisible(!1),d=!1,p=!1,f=!0,c.viewer.cameraControl.pointerEnabled=!0))}),!0),h.addEventListener("mousemove",(function(e){r.getActive()&&0===e.button&&p&&(clearTimeout(A),d&&(o=e.pageX,a=e.pageY,u=e.offsetX,c.setMarqueeVisible(!0),c.setMarqueeCorner2([o,a]),c.setPickMode(l1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.viewer=t,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==i.active,this._visible=!1,this._running=!1,this._destroyed=!1}return C(e,[{key:"start",value:function(e){var t=this;if(!this._destroyed){this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.marginLeft="".concat(this._circlePos[0]-this._circleRadius,"px"),this._circleDiv.style.marginTop="".concat(this._circlePos[1]-this._circleRadius,"px");var i,r=this._circleMaxRadius;this._running=!0,requestAnimationFrame((function e(s){if(t._running){i||(i=s);var n=s-i,o=Math.min(n/300,1),a=r+(2-r)*o;t._circleRadius=a,t._circleDiv.style.width="".concat(t._circleRadius,"px"),t._circleDiv.style.height="".concat(t._circleRadius,"px"),t._circleDiv.style.marginLeft="".concat(t._circlePos[0]-t._circleRadius/2,"px"),t._circleDiv.style.marginTop="".concat(t._circlePos[1]-t._circleRadius/2,"px"),o<1&&requestAnimationFrame(e)}})),this._circleDiv.style.visibility="visible"}}},{key:"stop",value:function(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius="".concat(this._circleRadius,"px"),this._circleDiv.style.visibility="hidden")}},{key:"durationMs",get:function(){return this._durationMs},set:function(e){this.stop(),this._durationMs=e}},{key:"destroy",value:function(){this._destroyed||(this.stop(),document.body.removeChild(this._circleDiv),this._destroyed=!0)}}]),e}(),Se=function(){function e(t,i,r){x(this,e),this.id=r&&r.id?r.id:t,this.viewer=i,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,i.addPlugin(this)}return C(e,[{key:"scheduleTask",value:function(e){_e.scheduleTask(e,null)}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);var r,s=this._eventSubs[e];if(s)for(var n in s)s.hasOwnProperty(n)&&(r=s[n],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}},{key:"on",value:function(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Q),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});var r=this._eventSubs[e];r?this._eventSubsNum[e]++:(r={},this._eventSubs[e]=r,this._eventSubsNum[e]=1);var s=this._subIdMap.addItem();r[s]={callback:t,scope:i||this},this._subIdEvents[s]=e;var n=this._events[e];return void 0!==n&&t.call(i||this,n),s}},{key:"off",value:function(e){if(null!=e&&this._subIdEvents){var t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];var i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}}},{key:"once",value:function(e,t,i){var r=this,s=this.on(e,(function(e){r.off(s),t.call(i||this,e)}),i)}},{key:"hasSubs",value:function(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}},{key:"log",value:function(e){console.log("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"warn",value:function(e){console.warn("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"error",value:function(e){console.error("[xeokit plugin ".concat(this.id,"]: ").concat(e))}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.removePlugin(this)}}]),e}(),Te=$.vec3(),Le=function(){var e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(r,s,n){return n=n||e,t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=1,$.transformVec4(r,t,i),$.setMat4Translation(r,i,n),n.slice()}}();function Re(e,t,i){var r=Float32Array.from([e[0]])[0],s=e[0]-r,n=Float32Array.from([e[1]])[0],o=e[1]-n,a=Float32Array.from([e[2]])[0],l=e[2]-a;t[0]=r,t[1]=n,t[2]=a,i[0]=s,i[1]=o,i[2]=l}function Ue(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1e3,s=$.getPositionsCenter(e,Te),n=Math.round(s[0]/r)*r,o=Math.round(s[1]/r)*r,a=Math.round(s[2]/r)*r;i[0]=n,i[1]=o,i[2]=a;var l=0!==i[0]||0!==i[1]||0!==i[2];if(l)for(var u=0,A=e.length;u0?this.meshes[0]._colorize[3]/255:1},set:function(e){if(0!==this.meshes.length){var t=null!=e,i=this.meshes[0]._colorize[3],r=255;if(t){if(e<0?e=0:e>1&&(e=1),i===(r=Math.floor(255*e)))return}else if(i===(r=255))return;for(var s=0,n=this.meshes.length;s1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._color=r.color||"black",this._highlightClass="viewer-ruler-wire-highlighted",this._wire=document.createElement("div"),this._wire.className+=this._wire.className?" viewer-ruler-wire":"viewer-ruler-wire",this._wireClickable=document.createElement("div"),this._wireClickable.className+=this._wireClickable.className?" viewer-ruler-wire-clickable":"viewer-ruler-wire-clickable",this._thickness=r.thickness||1,this._thicknessClickable=r.thicknessClickable||6,this._visible=!0,this._culled=!1;var s=this._wire,n=s.style;n.border="solid "+this._thickness+"px "+this._color,n.position="absolute",n["z-index"]=void 0===r.zIndex?"2000001":r.zIndex,n.width="0px",n.height="0px",n.visibility="visible",n.top="0px",n.left="0px",n["-webkit-transform-origin"]="0 0",n["-moz-transform-origin"]="0 0",n["-ms-transform-origin"]="0 0",n["-o-transform-origin"]="0 0",n["transform-origin"]="0 0",n["-webkit-transform"]="rotate(0deg)",n["-moz-transform"]="rotate(0deg)",n["-ms-transform"]="rotate(0deg)",n["-o-transform"]="rotate(0deg)",n.transform="rotate(0deg)",n.opacity=1,n["pointer-events"]="none",r.onContextMenu,t.appendChild(s);var o=this._wireClickable,a=o.style;a.border="solid "+this._thicknessClickable+"px "+this._color,a.position="absolute",a["z-index"]=void 0===r.zIndex?"2000002":r.zIndex+1,a.width="0px",a.height="0px",a.visibility="visible",a.top="0px",a.left="0px",a["-webkit-transform-origin"]="0 0",a["-moz-transform-origin"]="0 0",a["-ms-transform-origin"]="0 0",a["-o-transform-origin"]="0 0",a["transform-origin"]="0 0",a["-webkit-transform"]="rotate(0deg)",a["-moz-transform"]="rotate(0deg)",a["-ms-transform"]="rotate(0deg)",a["-o-transform"]="rotate(0deg)",a.transform="rotate(0deg)",a.opacity=0,a["pointer-events"]="none",r.onContextMenu,t.appendChild(o),r.onMouseOver&&o.addEventListener("mouseover",(function(e){r.onMouseOver(e,i)})),r.onMouseLeave&&o.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,i)})),r.onMouseWheel&&o.addEventListener("wheel",(function(e){r.onMouseWheel(e,i)})),r.onMouseDown&&o.addEventListener("mousedown",(function(e){r.onMouseDown(e,i)})),r.onMouseUp&&o.addEventListener("mouseup",(function(e){r.onMouseUp(e,i)})),r.onMouseMove&&o.addEventListener("mousemove",(function(e){r.onMouseMove(e,i)})),r.onContextMenu&&(tt()?(o.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,r.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),o.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):o.addEventListener("contextmenu",(function(e){console.log(e),r.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),this._x1=0,this._y1=0,this._x2=0,this._y2=0,this._update()}return C(e,[{key:"visible",get:function(){return"visible"===this._wire.style.visibility}},{key:"_update",value:function(){var e=Math.abs(Math.sqrt((this._x1-this._x2)*(this._x1-this._x2)+(this._y1-this._y2)*(this._y1-this._y2))),t=180*Math.atan2(this._y2-this._y1,this._x2-this._x1)/Math.PI,i=this._wire.style;i.width=Math.round(e)+"px",i.left=Math.round(this._x1)+"px",i.top=Math.round(this._y1)+"px",i["-webkit-transform"]="rotate("+t+"deg)",i["-moz-transform"]="rotate("+t+"deg)",i["-ms-transform"]="rotate("+t+"deg)",i["-o-transform"]="rotate("+t+"deg)",i.transform="rotate("+t+"deg)";var r=this._wireClickable.style;r.width=Math.round(e)+"px",r.left=Math.round(this._x1)+"px",r.top=Math.round(this._y1)+"px",r["-webkit-transform"]="rotate("+t+"deg)",r["-moz-transform"]="rotate("+t+"deg)",r["-ms-transform"]="rotate("+t+"deg)",r["-o-transform"]="rotate("+t+"deg)",r.transform="rotate("+t+"deg)"}},{key:"setStartAndEnd",value:function(e,t,i,r){this._x1=e,this._y1=t,this._x2=i,this._y2=r,this._update()}},{key:"setColor",value:function(e){this._color=e||"black",this._wire.style.border="solid "+this._thickness+"px "+this._color}},{key:"setOpacity",value:function(e){this._wire.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._wire.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._wireClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._wire.classList.add(this._highlightClass):this._wire.classList.remove(this._highlightClass))}},{key:"destroy",value:function(e){this._wire.parentElement&&this._wire.parentElement.removeChild(this._wire),this._wireClickable.parentElement&&this._wireClickable.parentElement.removeChild(this._wireClickable)}}]),e}(),rt=function(){function e(t){var i=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._highlightClass="viewer-ruler-dot-highlighted",this._x=0,this._y=0,this._dot=document.createElement("div"),this._dot.className+=this._dot.className?" viewer-ruler-dot":"viewer-ruler-dot",this._dotClickable=document.createElement("div"),this._dotClickable.className+=this._dotClickable.className?" viewer-ruler-dot-clickable":"viewer-ruler-dot-clickable",this._visible=!!r.visible,this._culled=!1;var s=this._dot,n=s.style;n["border-radius"]="25px",n.border="solid 2px white",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===r.zIndex?"40000005":r.zIndex,n.width="8px",n.height="8px",n.visibility=!1!==r.visible?"visible":"hidden",n.top="0px",n.left="0px",n["box-shadow"]="0 2px 5px 0 #182A3D;",n.opacity=1,n["pointer-events"]="none",r.onContextMenu,t.appendChild(s);var o=this._dotClickable,a=o.style;a["border-radius"]="35px",a.border="solid 10px white",a.position="absolute",a["z-index"]=void 0===r.zIndex?"40000007":r.zIndex+1,a.width="8px",a.height="8px",a.visibility="visible",a.top="0px",a.left="0px",a.opacity=0,a["pointer-events"]="none",r.onContextMenu,t.appendChild(o),o.addEventListener("click",(function(e){t.dispatchEvent(new MouseEvent("mouseover",e))})),r.onMouseOver&&o.addEventListener("mouseover",(function(e){r.onMouseOver(e,i),t.dispatchEvent(new MouseEvent("mouseover",e))})),r.onMouseLeave&&o.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,i)})),r.onMouseWheel&&o.addEventListener("wheel",(function(e){r.onMouseWheel(e,i)})),r.onMouseDown&&o.addEventListener("mousedown",(function(e){r.onMouseDown(e,i)})),r.onMouseUp&&o.addEventListener("mouseup",(function(e){r.onMouseUp(e,i)})),r.onMouseMove&&o.addEventListener("mousemove",(function(e){r.onMouseMove(e,i)})),r.onContextMenu&&(tt()?(o.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,r.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),o.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):o.addEventListener("contextmenu",(function(e){console.log(e),r.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")}))),r.onTouchstart&&o.addEventListener("touchstart",(function(e){r.onTouchstart(e,i)})),r.onTouchmove&&o.addEventListener("touchmove",(function(e){r.onTouchmove(e,i)})),r.onTouchend&&o.addEventListener("touchend",(function(e){r.onTouchend(e,i)})),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.borderColor)}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._dot.style;i.left=Math.round(e)-4+"px",i.top=Math.round(t)-4+"px";var r=this._dotClickable.style;r.left=Math.round(e)-9+"px",r.top=Math.round(t)-9+"px"}},{key:"setFillColor",value:function(e){this._dot.style.background=e||"lightgreen"}},{key:"setBorderColor",value:function(e){this._dot.style.border="solid 2px"+(e||"black")}},{key:"setOpacity",value:function(e){this._dot.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._dot.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setClickable",value:function(e){this._dotClickable.style["pointer-events"]=e?"all":"none"}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._dot.classList.add(this._highlightClass):this._dot.classList.remove(this._highlightClass))}},{key:"destroy",value:function(){this.setVisible(!1),this._dot.parentElement&&this._dot.parentElement.removeChild(this._dot),this._dotClickable.parentElement&&this._dotClickable.parentElement.removeChild(this._dotClickable)}}]),e}(),st=function(){function e(t){var i=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this._highlightClass="viewer-ruler-label-highlighted",this._prefix=r.prefix||"",this._x=0,this._y=0,this._visible=!0,this._culled=!1,this._label=document.createElement("div"),this._label.className+=this._label.className?" viewer-ruler-label":"viewer-ruler-label",this._timeout=null;var s=this._label,n=s.style;n["border-radius"]="5px",n.color="white",n.padding="4px",n.border="solid 1px",n.background="lightgreen",n.position="absolute",n["z-index"]=void 0===r.zIndex?"5000005":r.zIndex,n.width="auto",n.height="auto",n.visibility="visible",n.top="0px",n.left="0px",n["pointer-events"]="all",n.opacity=1,r.onContextMenu,s.innerText="",t.appendChild(s),this.setPos(r.x||0,r.y||0),this.setFillColor(r.fillColor),this.setBorderColor(r.fillColor),this.setText(r.text),r.onMouseOver&&s.addEventListener("mouseover",(function(e){r.onMouseOver(e,i),e.preventDefault()})),r.onMouseLeave&&s.addEventListener("mouseleave",(function(e){r.onMouseLeave(e,i),e.preventDefault()})),r.onMouseWheel&&s.addEventListener("wheel",(function(e){r.onMouseWheel(e,i)})),r.onMouseDown&&s.addEventListener("mousedown",(function(e){r.onMouseDown(e,i),e.stopPropagation()})),r.onMouseUp&&s.addEventListener("mouseup",(function(e){r.onMouseUp(e,i),e.stopPropagation()})),r.onMouseMove&&s.addEventListener("mousemove",(function(e){r.onMouseMove(e,i)})),r.onContextMenu&&(tt()?(s.addEventListener("touchstart",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null),i._timeout=setTimeout((function(){e.clientX=e.touches[0].clientX,e.clientY=e.touches[0].clientY,r.onContextMenu(e,i),clearTimeout(i._timeout),i._timeout=null}),500)})),s.addEventListener("touchend",(function(e){e.preventDefault(),i._timeout&&(clearTimeout(i._timeout),i._timeout=null)}))):s.addEventListener("contextmenu",(function(e){console.log(e),r.onContextMenu(e,i),e.preventDefault(),e.stopPropagation(),console.log("Label context menu")})))}return C(e,[{key:"setPos",value:function(e,t){this._x=e,this._y=t;var i=this._label.style;i.left=Math.round(e)-20+"px",i.top=Math.round(t)-12+"px"}},{key:"setPosOnWire",value:function(e,t,i,r){var s=e+.5*(i-e),n=t+.5*(r-t),o=this._label.style;o.left=Math.round(s)-20+"px",o.top=Math.round(n)-12+"px"}},{key:"setPosBetweenWires",value:function(e,t,i,r,s,n){var o=(e+i+s)/3,a=(t+r+n)/3,l=this._label.style;l.left=Math.round(o)-20+"px",l.top=Math.round(a)-12+"px"}},{key:"setText",value:function(e){this._label.innerHTML=this._prefix+(e||"")}},{key:"setFillColor",value:function(e){this._fillColor=e||"lightgreen",this._label.style.background=this._fillColor}},{key:"setBorderColor",value:function(e){this._borderColor=e||"black",this._label.style.border="solid 1px "+this._borderColor}},{key:"setOpacity",value:function(e){this._label.style.opacity=e}},{key:"setVisible",value:function(e){this._visible!==e&&(this._visible=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setCulled",value:function(e){this._culled!==e&&(this._culled=!!e,this._label.style.visibility=this._visible&&!this._culled?"visible":"hidden")}},{key:"setHighlighted",value:function(e){this._highlighted!==e&&(this._highlighted=!!e,this._highlighted?this._label.classList.add(this._highlightClass):this._label.classList.remove(this._highlightClass))}},{key:"setClickable",value:function(e){this._label.style["pointer-events"]=e?"all":"none"}},{key:"setPrefix",value:function(e){this._prefix!==e&&(this._prefix=e)}},{key:"destroy",value:function(){this._label.parentElement&&this._label.parentElement.removeChild(this._label)}}]),e}(),nt=$.vec3(),ot=$.vec3(),at=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,e.viewer.scene,s)).plugin=e,r._container=s.container,!r._container)throw"config missing: container";r._color=s.color||e.defaultColor;var n=r.plugin.viewer.scene;r._originMarker=new et(n,s.origin),r._cornerMarker=new et(n,s.corner),r._targetMarker=new et(n,s.target),r._originWorld=$.vec3(),r._cornerWorld=$.vec3(),r._targetWorld=$.vec3(),r._wp=new Float64Array(12),r._vp=new Float64Array(12),r._pp=new Float64Array(12),r._cp=new Int16Array(6);var o=s.onMouseOver?function(e){s.onMouseOver(e,b(r)),r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=s.onMouseLeave?function(e){s.onMouseLeave(e,b(r)),r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=s.onContextMenu?function(e){s.onContextMenu(e,b(r))}:null,u=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))},A=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},c=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},h=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))};return r._originDot=new rt(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._cornerDot=new rt(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._targetDot=new rt(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._originWire=new it(r._container,{color:r._color||"blue",thickness:1,zIndex:e.zIndex,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._targetWire=new it(r._container,{color:r._color||"red",thickness:1,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._angleLabel=new st(r._container,{fillColor:r._color||"#00BBFF",prefix:"",text:"",zIndex:e.zIndex+2,onMouseOver:o,onMouseLeave:a,onMouseWheel:u,onMouseDown:A,onMouseUp:c,onMouseMove:h,onContextMenu:l}),r._wpDirty=!1,r._vpDirty=!1,r._cpDirty=!1,r._visible=!1,r._originVisible=!1,r._cornerVisible=!1,r._targetVisible=!1,r._originWireVisible=!1,r._targetWireVisible=!1,r._angleVisible=!1,r._labelsVisible=!1,r._clickable=!1,r._originMarker.on("worldPos",(function(e){r._originWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._cornerMarker.on("worldPos",(function(e){r._cornerWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._targetMarker.on("worldPos",(function(e){r._targetWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._onViewMatrix=n.camera.on("viewMatrix",(function(){r._vpDirty=!0,r._needUpdate(0)})),r._onProjMatrix=n.camera.on("projMatrix",(function(){r._cpDirty=!0,r._needUpdate()})),r._onCanvasBoundary=n.canvas.on("boundary",(function(){r._cpDirty=!0,r._needUpdate(0)})),r._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){r._sectionPlanesDirty=!0,r._needUpdate()})),r.approximate=s.approximate,r.visible=s.visible,r.originVisible=s.originVisible,r.cornerVisible=s.cornerVisible,r.targetVisible=s.targetVisible,r.originWireVisible=s.originWireVisible,r.targetWireVisible=s.targetWireVisible,r.angleVisible=s.angleVisible,r.labelsVisible=s.labelsVisible,r}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._cornerWorld[0],this._wp[5]=this._cornerWorld[1],this._wp[6]=this._cornerWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._targetWorld[2],this._wp[11]=1,this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._wp))return this._angleLabel.setCulled(!0),this._originWire.setCulled(!0),this._targetWire.setCulled(!0),this._originDot.setCulled(!0),this._cornerDot.setCulled(!0),void this._targetDot.setCulled(!0);this._angleLabel.setCulled(!1),this._originWire.setCulled(!1),this._targetWire.setCulled(!1),this._originDot.setCulled(!1),this._cornerDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}if(this._cpDirty){var t=-.3,i=this._originMarker.viewPos[2],r=this._cornerMarker.viewPos[2],s=this._targetMarker.viewPos[2];if(i>t||r>t||s>t)return this._originDot.setVisible(!1),this._cornerDot.setVisible(!1),this._targetDot.setVisible(!1),this._originWire.setVisible(!1),this._targetWire.setVisible(!1),void this._angleLabel.setCulled(!0);$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var n=this._pp,o=this._cp,a=e.canvas.canvas.getBoundingClientRect(),l=this._container.getBoundingClientRect(),u=a.top-l.top,A=a.left-l.left,c=e.canvas.boundary,h=c[2],d=c[3],p=0,f=0,v=n.length;f1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene))._canvasToPagePos=s.canvasToPagePos,r.pointerLens=s.pointerLens,r._active=!1,r._mouseState=0,r._currentAngleMeasurement=null,r._initMarkerDiv(),r._onMouseHoverSurface=null,r._onHoverNothing=null,r._onPickedNothing=null,r._onPickedSurface=null,r._onInputMouseDown=null,r._onInputMouseUp=null,r._snapping=!1!==s.snapping,r._attachPlugin(e,s),r}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this.markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this.markerDiv||this._initMarkerDiv(),this.angleMeasurementsPlugin;var t=this.scene;t.input;var i=t.canvas.canvas,r=this.angleMeasurementsPlugin.viewer.cameraControl,s=this.pointerLens,n=!1,o=null,a=0,l=0,u=$.vec3(),A=$.vec2();this._currentAngleMeasurement=null;var c=function e(t){return t.offsetTop+(t.offsetParent&&t.offsetParent!==i.parentNode&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&t.offsetParent!==i.parentNode&&e(t.offsetParent))},d=$.vec2();this._onMouseHoverSurface=r.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){t.snappedToVertex||t.snappedToEdge?(s&&(s.visible=!0,s.canvasPos=t.canvasPos,s.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,s.snapped=!0),e.markerDiv.style.background="greenyellow",e.markerDiv.style.border="2px solid green"):(s&&(s.visible=!0,s.canvasPos=t.canvasPos,s.snappedCanvasPos=t.canvasPos,s.snapped=!1),e.markerDiv.style.background="pink",e.markerDiv.style.border="2px solid red");var r=t.snappedCanvasPos||t.canvasPos;switch(n=!0,o=t.entity,u.set(t.worldPos),A.set(r),e._mouseState){case 0:e._canvasToPagePos?(e._canvasToPagePos(i,r,d),e.markerDiv.style.left="".concat(d[0]-5,"px"),e.markerDiv.style.top="".concat(d[1]-5,"px")):(e.markerDiv.style.left="".concat(h(i)+r[0]-5,"px"),e.markerDiv.style.top="".concat(c(i)+r[1]-5,"px"));break;case 1:e._currentAngleMeasurement&&(e._currentAngleMeasurement.originWireVisible=!0,e._currentAngleMeasurement.targetWireVisible=!1,e._currentAngleMeasurement.cornerVisible=!0,e._currentAngleMeasurement.angleVisible=!1,e._currentAngleMeasurement.corner.worldPos=t.worldPos,e._currentAngleMeasurement.corner.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer";break;case 2:e._currentAngleMeasurement&&(e._currentAngleMeasurement.targetWireVisible=!0,e._currentAngleMeasurement.targetVisible=!0,e._currentAngleMeasurement.angleVisible=!0,e._currentAngleMeasurement.target.worldPos=t.worldPos,e._currentAngleMeasurement.target.entity=t.entity),e.markerDiv.style.left="-10000px",e.markerDiv.style.top="-10000px",i.style.cursor="pointer"}})),i.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(a=e.clientX,l=e.clientY)}),i.addEventListener("mouseup",this._onMouseUp=function(t){if(1===t.which&&!(t.clientX>a+20||t.clientXl+20||t.clientY1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"AngleMeasurements",e))._container=s.container||document.body,r._defaultControl=null,r._measurements={},r.defaultColor=void 0!==s.defaultColor?s.defaultColor:"#00BBFF",r.defaultLabelsVisible=!1!==s.defaultLabelsVisible,r.zIndex=s.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:b(r),angleMeasurement:t,measurement:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:b(r),angleMeasurement:t,measurement:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:b(r),angleMeasurement:t,measurement:t,event:e})},r}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new ut(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,r=t.corner,s=t.target,n=new at(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},corner:{entity:r.entity,worldPos:r.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:t.visible,originVisible:!0,originWireVisible:!0,cornerVisible:!0,targetWireVisible:!0,targetVisible:!0,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[n.id]=n,n.on("destroyed",(function(){delete e._measurements[n.id]})),n.clickable=!0,this.fire("measurementCreated",n),n}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("AngleMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e.viewer.scene)).pointerLens=s.pointerLens,r.pointerCircle=new De(e.viewer),r._active=!1;var n=document.createElement("div"),o=r.scene.canvas.canvas;return o.parentNode.insertBefore(n,o),n.style.background="black",n.style.border="2px solid blue",n.style.borderRadius="10px",n.style.width="5px",n.style.height="5px",n.style.margin="-200px -200px",n.style.zIndex="100",n.style.position="absolute",n.style.pointerEvents="none",r.markerDiv=n,r._currentAngleMeasurement=null,r._onCanvasTouchStart=null,r._onCanvasTouchEnd=null,r._longTouchTimeoutMs=300,r._snapping=!1!==s.snapping,r._touchState=0,r._attachPlugin(e,s),r}return C(i,[{key:"_attachPlugin",value:function(e){this.angleMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){var t=this.plugin,i=this.scene,r=i.canvas.canvas;t.pointerLens;var s=$.vec3(),n=20,o=null;this._touchState=0;var a=$.vec2(),l=$.vec2(),u=$.vec2(),A=null,c=function(){e.plugin.viewer.cameraControl.active=!1},h=function(){e.plugin.viewer.cameraControl.active=!0};r.addEventListener("touchstart",this._onCanvasTouchStart=function(r){var u=r.touches.length;if(1===u){var d=r.touches[0],p=d.clientX,f=d.clientY;switch(a.set([p,f]),l.set([p,f]),e._touchState){case 0:if(1!==u&&null!==o)return o&&(clearTimeout(o),o=null),e._currentAngleMeasurement&&(e._currentAngleMeasurement.destroy(),e._currentAngleMeasurement=null),h(),void(e._touchState=0);var v=i.pick({canvasPos:l,snapToVertex:e._snapping,snapToEdge:e._snapping});if(v&&v.snapped)s.set(v.worldPos),e.pointerCircle.start(v.snappedCanvasPos);else{var g=i.pick({canvasPos:l,pickSurface:!0});if(!g||!g.worldPos)return;s.set(g.worldPos),e.pointerCircle.start(g.canvasPos)}o=setTimeout((function(){1!==u||l[0]>a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||da[1]+n||pa[0]+n||da[1]+n||pa[0]+n||da[1]+n||p

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

";le.isArray(r)&&(r=r.join("")),r=this._renderTemplate(r.trim());var s=document.createRange().createContextualFragment(r);this._label=s.firstChild,this._container.appendChild(this._label),this._label.style.visibility=this._markerShown&&this._labelShown?"visible":"hidden",this._label.addEventListener("wheel",(function(t){e.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",t))}))}}},{key:"_updatePosition",value:function(){var e=this.scene.canvas.boundary,t=e[0],i=e[1],r=this.canvasPos;this._marker.style.left=Math.floor(t+r[0])-12+"px",this._marker.style.top=Math.floor(i+r[1])-12+"px",this._marker.style["z-index"]=90005+Math.floor(this._viewPos[2])+1;this._label.style.left=20+Math.floor(t+r[0]+20)+"px",this._label.style.top=Math.floor(i+r[1]+-17)+"px",this._label.style["z-index"]=90005+Math.floor(this._viewPos[2])+1}},{key:"_renderTemplate",value:function(e){for(var t in this._values)if(this._values.hasOwnProperty(t)){var i=this._values[t];e=e.replace(new RegExp("{{"+t+"}}","g"),i)}return e}},{key:"setMarkerShown",value:function(e){e=!!e,this._markerShown!==e&&(this._markerShown=e,this._visibilityDirty=!0)}},{key:"getMarkerShown",value:function(){return this._markerShown}},{key:"setLabelShown",value:function(e){e=!!e,this._labelShown!==e&&(this._labelShown=e,this._visibilityDirty=!0)}},{key:"getLabelShown",value:function(){return this._labelShown}},{key:"setField",value:function(e,t){this._values[e]=t||"",this._htmlDirty=!0}},{key:"getField",value:function(e){return this._values[e]}},{key:"setValues",value:function(e){for(var t in e)if(e.hasOwnProperty(t)){var i=e[t];this.setField(t,i)}}},{key:"getValues",value:function(){return this._values}},{key:"destroy",value:function(){this._marker&&(this._markerExternal?(this._marker.removeEventListener("click",this._onMouseClickedExternalMarker),this._marker.removeEventListener("mouseenter",this._onMouseEnterExternalMarker),this._marker.removeEventListener("mouseleave",this._onMouseLeaveExternalMarker),this._marker=null):(this._marker.parentNode.removeChild(this._marker),this._marker=null)),this._label&&(this._labelExternal||this._label.parentNode.removeChild(this._label),this._label=null),this.scene.off(this._onTick),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),dt=$.vec3(),pt=$.vec3(),ft=$.vec3(),vt=function(e){g(i,Se);var t=_(i);function i(e,r){var s;return x(this,i),(s=t.call(this,"Annotations",e))._labelHTML=r.labelHTML||"
",s._markerHTML=r.markerHTML||"
",s._container=r.container||document.body,s._values=r.values||{},s.annotations={},s.surfaceOffset=r.surfaceOffset,s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){if("clearAnnotations"===e)this.clear()}},{key:"surfaceOffset",get:function(){return this._surfaceOffset},set:function(e){null==e&&(e=.3),this._surfaceOffset=e}},{key:"createAnnotation",value:function(e){var t,i,r=this;if(this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),e.pickResult=e.pickResult||e.pickRecord,e.pickResult){var s=e.pickResult;if(s.worldPos&&s.worldNormal){var n=$.normalizeVec3(s.worldNormal,dt),o=$.mulVec3Scalar(n,this._surfaceOffset,pt);t=$.addVec3(s.worldPos,o,ft),i=s.entity}else this.error("Param 'pickResult' does not have both worldPos and worldNormal")}else t=e.worldPos,i=e.entity;var a=null;e.markerElementId&&((a=document.getElementById(e.markerElementId))||this.error("Can't find DOM element for 'markerElementId' value '"+e.markerElementId+"' - defaulting to internally-generated empty DIV"));var l=null;e.labelElementId&&((l=document.getElementById(e.labelElementId))||this.error("Can't find DOM element for 'labelElementId' value '"+e.labelElementId+"' - defaulting to internally-generated empty DIV"));var u=new ht(this.viewer.scene,{id:e.id,plugin:this,entity:i,worldPos:t,container:this._container,markerElement:a,labelElement:l,markerHTML:e.markerHTML||this._markerHTML,labelHTML:e.labelHTML||this._labelHTML,occludable:e.occludable,values:le.apply(e.values,le.apply(this._values,{})),markerShown:e.markerShown,labelShown:e.labelShown,eye:e.eye,look:e.look,up:e.up,projection:e.projection,visible:!1!==e.visible});return this.annotations[u.id]=u,u.on("destroyed",(function(){delete r.annotations[u.id],r.fire("annotationDestroyed",u.id)})),this.fire("annotationCreated",u.id),u}},{key:"destroyAnnotation",value:function(e){var t=this.annotations[e];t?t.destroy():this.log("Annotation not found: "+e)}},{key:"clear",value:function(){for(var e=Object.keys(this.annotations),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._canvas=s.canvas,r._element=null,r._isCustom=!1,s.elementId&&(r._element=document.getElementById(s.elementId),r._element?r._adjustPosition():r.error("Can't find given Spinner HTML element: '"+s.elementId+"' - will automatically create default element")),r._element||r._createDefaultSpinner(),r.processes=0,r}return C(i,[{key:"type",get:function(){return"Spinner"}},{key:"_createDefaultSpinner",value:function(){this._injectDefaultCSS();var e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='
',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}},{key:"_injectDefaultCSS",value:function(){var e="xeokit-spinner-css";if(!document.getElementById(e)){var t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}}},{key:"_adjustPosition",value:function(){if(!this._isCustom){var e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}}},{key:"processes",get:function(){return this._processes},set:function(e){if(e=e||0,this._processes!==e&&!(e<0)){var t=this._processes;this._processes=e;var i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}}},{key:"_destroy",value:function(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);var e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}]),i}(),mt=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"],_t=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s))._backgroundColor=$.vec3([s.backgroundColor?s.backgroundColor[0]:1,s.backgroundColor?s.backgroundColor[1]:1,s.backgroundColor?s.backgroundColor[2]:1]),r._backgroundColorFromAmbientLight=!!s.backgroundColorFromAmbientLight,r.canvas=s.canvas,r.gl=null,r.webgl2=!1,r.transparent=!!s.transparent,r.contextAttr=s.contextAttr||{},r.contextAttr.alpha=r.transparent,r.contextAttr.preserveDrawingBuffer=!!r.contextAttr.preserveDrawingBuffer,r.contextAttr.stencil=!1,r.contextAttr.premultipliedAlpha=!!r.contextAttr.premultipliedAlpha,r.contextAttr.antialias=!1!==r.contextAttr.antialias,r.resolutionScale=s.resolutionScale,r.canvas.width=Math.round(r.canvas.clientWidth*r._resolutionScale),r.canvas.height=Math.round(r.canvas.clientHeight*r._resolutionScale),r.boundary=[r.canvas.offsetLeft,r.canvas.offsetTop,r.canvas.clientWidth,r.canvas.clientHeight],r._initWebGL(s);var n=b(r);r.canvas.addEventListener("webglcontextlost",r._webglcontextlostListener=function(e){console.time("webglcontextrestored"),n.scene._webglContextLost(),n.fire("webglcontextlost"),e.preventDefault()},!1),r.canvas.addEventListener("webglcontextrestored",r._webglcontextrestoredListener=function(e){n._initWebGL(),n.gl&&(n.scene._webglContextRestored(n.gl),n.fire("webglcontextrestored",n.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);var o=!0,a=new ResizeObserver((function(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){t.value.contentBoxSize&&(o=!0)}}catch(e){i.e(e)}finally{i.f()}}));return a.observe(r.canvas),r._tick=r.scene.on("tick",(function(){o&&(o=!1,n.canvas.width=Math.round(n.canvas.clientWidth*n._resolutionScale),n.canvas.height=Math.round(n.canvas.clientHeight*n._resolutionScale),n.boundary[0]=n.canvas.offsetLeft,n.boundary[1]=n.canvas.offsetTop,n.boundary[2]=n.canvas.clientWidth,n.boundary[3]=n.canvas.clientHeight,n.fire("boundary",n.boundary))})),r._spinner=new gt(r.scene,{canvas:r.canvas,elementId:s.spinnerElementId}),r}return C(i,[{key:"type",get:function(){return"Canvas"}},{key:"backgroundColorFromAmbientLight",get:function(){return this._backgroundColorFromAmbientLight},set:function(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}},{key:"backgroundColor",get:function(){return this._backgroundColor},set:function(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}},{key:"resolutionScale",get:function(){return this._resolutionScale},set:function(e){if((e=e||1)!==this._resolutionScale){this._resolutionScale=e;var t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}}},{key:"spinner",get:function(){return this._spinner}},{key:"_createCanvas",value:function(){var e="xeokit-canvas-"+$.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),r=i.style;r.height="100%",r.width="100%",r.padding="0",r.margin="0",r.background="rgba(0,0,0,0);",r.float="left",r.left="0",r.top="0",r.position="absolute",r.opacity="1.0",r["z-index"]="-10000",i.innerHTML+='',t.appendChild(i),this.canvas=document.getElementById(e)}},{key:"_getElementXY",value:function(e){for(var t=0,i=0;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}},{key:"_initWebGL",value:function(){if(!this.gl)for(var e=0;!this.gl&&e0?bt.FS_MAX_FLOAT_PRECISION="highp":Bt.getShaderPrecisionFormat(Bt.FRAGMENT_SHADER,Bt.MEDIUM_FLOAT).precision>0?bt.FS_MAX_FLOAT_PRECISION="mediump":bt.FS_MAX_FLOAT_PRECISION="lowp":bt.FS_MAX_FLOAT_PRECISION="mediump",bt.DEPTH_BUFFER_BITS=Bt.getParameter(Bt.DEPTH_BITS),bt.MAX_TEXTURE_SIZE=Bt.getParameter(Bt.MAX_TEXTURE_SIZE),bt.MAX_CUBE_MAP_SIZE=Bt.getParameter(Bt.MAX_CUBE_MAP_TEXTURE_SIZE),bt.MAX_RENDERBUFFER_SIZE=Bt.getParameter(Bt.MAX_RENDERBUFFER_SIZE),bt.MAX_TEXTURE_UNITS=Bt.getParameter(Bt.MAX_COMBINED_TEXTURE_IMAGE_UNITS),bt.MAX_TEXTURE_IMAGE_UNITS=Bt.getParameter(Bt.MAX_TEXTURE_IMAGE_UNITS),bt.MAX_VERTEX_ATTRIBS=Bt.getParameter(Bt.MAX_VERTEX_ATTRIBS),bt.MAX_VERTEX_UNIFORM_VECTORS=Bt.getParameter(Bt.MAX_VERTEX_UNIFORM_VECTORS),bt.MAX_FRAGMENT_UNIFORM_VECTORS=Bt.getParameter(Bt.MAX_FRAGMENT_UNIFORM_VECTORS),bt.MAX_VARYING_VECTORS=Bt.getParameter(Bt.MAX_VARYING_VECTORS),Bt.getSupportedExtensions().forEach((function(e){bt.SUPPORTED_EXTENSIONS[e]=!0})))}var xt=function(){function e(){x(this,e),this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}return C(e,[{key:"canvasPos",get:function(){return this._gotCanvasPos?this._canvasPos:null},set:function(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}},{key:"origin",get:function(){return this._gotOrigin?this._origin:null},set:function(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}},{key:"direction",get:function(){return this._gotDirection?this._direction:null},set:function(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}},{key:"indices",get:function(){return this.entity&&this._gotIndices?this._indices:null},set:function(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}},{key:"localPos",get:function(){return this.entity&&this._gotLocalPos?this._localPos:null},set:function(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}},{key:"snappedCanvasPos",get:function(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null},set:function(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}},{key:"worldPos",get:function(){return this._gotWorldPos?this._worldPos:null},set:function(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}},{key:"viewPos",get:function(){return this.entity&&this._gotViewPos?this._viewPos:null},set:function(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}},{key:"bary",get:function(){return this.entity&&this._gotBary?this._bary:null},set:function(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}},{key:"worldNormal",get:function(){return this.entity&&this._gotWorldNormal?this._worldNormal:null},set:function(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}},{key:"uv",get:function(){return this.entity&&this._gotUV?this._uv:null},set:function(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}},{key:"snapped",get:function(){return this.snappedToEdge||this.snappedToVertex}},{key:"reset",value:function(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}]),e}(),Pt=function(){function e(t,i,r){if(x(this,e),this.allocated=!1,this.compiled=!1,this.handle=t.createShader(i),this.handle){if(this.allocated=!0,t.shaderSource(this.handle,r),t.compileShader(this.handle),this.compiled=t.getShaderParameter(this.handle,t.COMPILE_STATUS),!this.compiled&&!t.isContextLost()){for(var s=r.split("\n"),n=[],o=0;o0&&"/"===t.charAt(i+1)&&(t=t.substring(0,i)),r.push(t);return r.join("\n")}function kt(e){console.error(e.join("\n"))}var It=function(){function e(t,i){x(this,e),this.id=Et.addItem({}),this.source=i,this.init(t)}return C(e,[{key:"init",value:function(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Pt(e,e.VERTEX_SHADER,Ft(this.source.vertex)),this._fragmentShader=new Pt(e,e.FRAGMENT_SHADER,Ft(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void kt(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void kt(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void kt(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void kt(this.errors);var t,i,r,s,n;if(this.compiled=!0,this.handle=e.createProgram(),this.handle){if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void kt(this.errors);var o=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;ithis.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}},{key:"setData",value:function(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}},{key:"bind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}},{key:"unbind",value:function(){this.allocated&&this._gl.bindBuffer(this.type,null)}},{key:"destroy",value:function(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}]),e}(),St=function(){function e(t,i){x(this,e),this.scene=t,this.aabb=$.AABB3(),this.origin=$.vec3(i),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}return C(e,[{key:"addMarker",value:function(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}},{key:"markerWorldPosUpdated",value:function(e){if(this.markers[e.id]){var t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}}},{key:"removeMarker",value:function(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}},{key:"update",value:function(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}},{key:"_buildMarkerList",value:function(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}},{key:"_buildPositions",value:function(){for(var e=0,t=0;t-t)a._setVisible(!1);else{var l=a.canvasPos,u=l[0],A=l[1];u+10<0||A+10<0||u-10>r||A-10>s?a._setVisible(!1):!a.entity||a.entity.visible?a.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=a,this.pixels[n++]=u,this.pixels[n++]=A):a._setVisible(!0):a._setVisible(!1)}}}},{key:"_updateActiveSectionPlanes",value:function(){var e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(var i=0;i0,i=[];return i.push("#version 300 es"),i.push("// OcclusionTester vertex shader"),i.push("in vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push(" vWorldPosition = worldPosition;"),i.push(" vec4 clipPos = projMatrix * viewPosition;"),i.push(" gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled?i.push("vFragDepth = 1.0 + clipPos.w;"):e.markerZOffset<0&&i.push("clipPos.z += "+e.markerZOffset+";"),i.push(" gl_Position = clipPos;"),i.push("}"),i}},{key:"_buildFragmentShaderSource",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,r=[];if(r.push("#version 300 es"),r.push("// OcclusionTester 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;");for(var s=0;s 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(1.0, 0.0, 0.0, 1.0); "),r.push("}"),r}},{key:"_buildProgram",value:function(){this._program&&this._program.destroy();var e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new It(t,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,n=i.sectionPlanes.length;s0)for(var h=r.sectionPlanes,d=0;d= ( 1.0 - EPSILON ) ) {\n \t\t\tcontinue;\n \t\t}\n\n \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n \t\tweightSum += 1.0;\n \t}\n\n \tif( weightSum == 0.0 ) discard;\n\n \treturn occlusionSum * ( uIntensity / weightSum );\n }\n\n out vec4 outColor;\n \n void main() {\n \n \tfloat centerDepth = getDepth( vUV );\n \t\n \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n \t\tdiscard;\n \t}\n\n \tfloat centerViewZ = getViewZ( centerDepth );\n \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n \n \toutColor = packFloatToRGBA( 1.0- ambientOcclusion );\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var r=new Float32Array([1,1,0,1,0,0,1,0]),s=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),n=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Dt(i,i.ARRAY_BUFFER,s,s.length,3,i.STATIC_DRAW),this._uvBuf=new Dt(i,i.ARRAY_BUFFER,r,r.length,2,i.STATIC_DRAW),this._indicesBuf=new Dt(i,i.ELEMENT_ARRAY_BUFFER,n,n.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}}},{key:"destroy",value:function(){this._program&&(this._program.destroy(),this._program=null)}}]),e}(),Nt=new Float32Array(zt(17,[0,1])),Qt=new Float32Array(zt(17,[1,0])),Vt=new Float32Array(function(e,t){for(var i=[],r=0;r<=e;r++)i.push(Gt(r,t));return i}(17,4)),Ht=new Float32Array(2),jt=function(){function e(t){x(this,e),this._scene=t,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}return C(e,[{key:"init",value:function(){var e=this._scene.canvas.gl;if(this._program=new It(e,{vertex:["#version 300 es\n precision highp float;\n precision highp int;\n \n in vec3 aPosition;\n in vec2 aUV;\n uniform vec2 uViewport;\n out vec2 vUV;\n out vec2 vInvSize;\n void main () {\n vUV = aUV;\n vInvSize = 1.0 / uViewport;\n gl_Position = vec4(aPosition, 1.0);\n }"],fragment:["#version 300 es\n precision highp float;\n precision highp int;\n \n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define EPSILON 1e-6\n\n #define KERNEL_RADIUS ".concat(16,"\n\n in vec2 vUV;\n in vec2 vInvSize;\n \n uniform sampler2D uDepthTexture;\n uniform sampler2D uOcclusionTexture; \n \n uniform float uCameraNear;\n uniform float uCameraFar; \n uniform float uDepthCutoff;\n\n uniform vec2 uSampleOffsets[ KERNEL_RADIUS + 1 ];\n uniform float uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n const float unpackDownscale = 255. / 256.; \n\n const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\n const vec4 unpackFactors = unpackDownscale / vec4( packFactors, 1. ); \n\n const float packUpscale = 256. / 255.;\n \n const float shiftRights = 1. / 256.;\n \n float unpackRGBAToFloat( const in vec4 v ) {\n return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n } \n\n vec4 packFloatToRGBA( const in float v ) {\n vec4 r = vec4( fract( v * packFactors ), v );\n r.yzw -= r.xyz * shiftRights; \n return r * packUpscale;\n }\n\n float viewZToOrthographicDepth( const in float viewZ) {\n return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n }\n \n float orthographicDepthToViewZ( const in float linearClipZ) {\n return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n }\n\n float viewZToPerspectiveDepth( const in float viewZ) {\n return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n }\n \n float perspectiveDepthToViewZ( const in float invClipZ) {\n return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n }\n\n float getDepth( const in vec2 screenPosition ) {\n return vec4(texture(uDepthTexture, screenPosition)).r;\n }\n\n float getViewZ( const in float depth ) {\n return perspectiveDepthToViewZ( depth );\n }\n\n out vec4 outColor;\n \n void main() {\n \n float depth = getDepth( vUV );\n if( depth >= ( 1.0 - EPSILON ) ) {\n discard;\n }\n\n float centerViewZ = -getViewZ( depth );\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = uSampleWeights[0];\n float occlusionSum = unpackRGBAToFloat(texture( uOcclusionTexture, vUV )) * weightSum;\n\n for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n float sampleWeight = uSampleWeights[i];\n vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n vec2 sampleUV = vUV + sampleUVOffset;\n float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n rBreak = true;\n }\n\n if( ! rBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n\n sampleUV = vUV - sampleUVOffset;\n viewZ = -getViewZ( getDepth( sampleUV ) );\n\n if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n lBreak = true;\n }\n\n if( ! lBreak ) {\n occlusionSum += unpackRGBAToFloat(texture( uOcclusionTexture, sampleUV )) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n outColor = packFloatToRGBA(occlusionSum / weightSum);\n }")]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);var t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),r=new Uint32Array([0,1,2,0,2,3]);this._positionsBuf=new Dt(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new Dt(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new Dt(e,e.ELEMENT_ARRAY_BUFFER,r,r.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}},{key:"render",value:function(e,t,i){var r=this;if(!this._programError){this._getInverseProjectMat||(this._getInverseProjectMat=function(){var e=!0;r._scene.camera.on("projMatrix",(function(){e=!0}));var t=$.mat4();return function(){return e&&$.inverseMat4(o.camera.projMatrix,t),t}}());var s=this._scene.canvas.gl,n=this._program,o=this._scene,a=s.drawingBufferWidth,l=s.drawingBufferHeight,u=o.camera.project._state,A=u.near,c=u.far;s.viewport(0,0,a,l),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),n.bind(),Ht[0]=a,Ht[1]=l,s.uniform2fv(this._uViewport,Ht),s.uniform1f(this._uCameraNear,A),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,Qt):s.uniform2fv(this._uSampleOffsets,Nt),s.uniform1fv(this._uSampleWeights,Vt);var h=e.getDepthTexture(),d=t.getTexture();n.bindTexture(this._uDepthTexture,h,0),n.bindTexture(this._uOcclusionTexture,d,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}}},{key:"destroy",value:function(){this._program.destroy()}}]),e}();function Gt(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function zt(e,t){for(var i=[],r=0;r<=e;r++)i.push(t[0]*r),i.push(t[1]*r);return i}var Wt=function(){function e(t,i,r){x(this,e),r=r||{},this.gl=i,this.allocated=!1,this.canvas=t,this.buffer=null,this.bound=!1,this.size=r.size,this._hasDepthTexture=!!r.depthTexture}return C(e,[{key:"setSize",value:function(e){this.size=e}},{key:"webglContextRestored",value:function(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}},{key:"bind",value:function(){if(this._touch.apply(this,arguments),!this.bound){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}},{key:"createTexture",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=this.gl,s=r.createTexture();return r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),i?r.texStorage2D(r.TEXTURE_2D,1,i,e,t):r.texImage2D(r.TEXTURE_2D,0,r.RGBA,e,t,0,r.RGBA,r.UNSIGNED_BYTE,null),s}},{key:"_touch",value:function(){var e,t,i=this,r=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=r.drawingBufferWidth,t=r.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;this.buffer.textures.forEach((function(e){return r.deleteTexture(e)})),r.deleteFramebuffer(this.buffer.framebuf),r.deleteRenderbuffer(this.buffer.renderbuf)}for(var s,n=[],o=arguments.length,a=new Array(o),l=0;l0?n.push.apply(n,A(a.map((function(r){return i.createTexture(e,t,r)})))):n.push(this.createTexture(e,t)),this._hasDepthTexture&&(s=r.createTexture(),r.bindTexture(r.TEXTURE_2D,s),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MAG_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_MIN_FILTER,r.NEAREST),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE),r.texParameteri(r.TEXTURE_2D,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE),r.texImage2D(r.TEXTURE_2D,0,r.DEPTH_COMPONENT32F,e,t,0,r.DEPTH_COMPONENT,r.FLOAT,null));var u=r.createRenderbuffer();r.bindRenderbuffer(r.RENDERBUFFER,u),r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_COMPONENT32F,e,t);var c=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,c);for(var h=0;h0&&r.drawBuffers(n.map((function(e,t){return r.COLOR_ATTACHMENT0+t}))),this._hasDepthTexture?r.framebufferTexture2D(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.TEXTURE_2D,s,0):r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,u),r.bindTexture(r.TEXTURE_2D,null),r.bindRenderbuffer(r.RENDERBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.bindFramebuffer(r.FRAMEBUFFER,c),!r.isFramebuffer(c))throw"Invalid framebuffer";r.bindFramebuffer(r.FRAMEBUFFER,null);var d=r.checkFramebufferStatus(r.FRAMEBUFFER);switch(d){case r.FRAMEBUFFER_COMPLETE:break;case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+d}this.buffer={framebuf:c,renderbuf:u,texture:n[0],textures:n,depthTexture:s,width:e,height:t},this.bound=!1}},{key:"clear",value:function(){if(!this.bound)throw"Render buffer not bound";var e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}},{key:"read",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:Uint8Array,n=arguments.length>5&&void 0!==arguments[5]?arguments[5]:4,o=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0,a=e,l=this.buffer.height?this.buffer.height-t-1:this.gl.drawingBufferHeight-t,u=new s(n),A=this.gl;return A.readBuffer(A.COLOR_ATTACHMENT0+o),A.readPixels(a,l,1,1,i||A.RGBA,r||A.UNSIGNED_BYTE,u,0),u}},{key:"readArray",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:Uint8Array,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:4,s=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,n=new i(this.buffer.width*this.buffer.height*r),o=this.gl;return o.readBuffer(o.COLOR_ATTACHMENT0+s),o.readPixels(0,0,this.buffer.width,this.buffer.height,e||o.RGBA,t||o.UNSIGNED_BYTE,n,0),n}},{key:"readImageAsCanvas",value:function(){var e=this.gl,t=this._getImageDataCache(),i=t.pixelData,r=t.canvas,s=t.imageData,n=t.context;e.readPixels(0,0,this.buffer.width,this.buffer.height,e.RGBA,e.UNSIGNED_BYTE,i);for(var o=this.buffer.width,a=this.buffer.height,l=a/2|0,u=4*o,A=new Uint8Array(4*o),c=0;c0&&void 0!==arguments[0]?arguments[0]:Uint8Array,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4,i=this.buffer.width,r=this.buffer.height,s=this._imageDataCache;if(s&&(s.width===i&&s.height===r||(this._imageDataCache=null,s=null)),!s){var n=document.createElement("canvas"),o=n.getContext("2d");n.width=i,n.height=r,s={pixelData:new e(i*r*t),canvas:n,context:o,imageData:o.createImageData(i,r),width:i,height:r},this._imageDataCache=s}return s.context.resetTransform(),s}},{key:"unbind",value:function(){var e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}},{key:"getTexture",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,t=this;return this._texture||(this._texture={renderBuffer:this,bind:function(i){return!(!t.buffer||!t.buffer.textures[e])&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,t.buffer.textures[e]),!0)},unbind:function(i){t.buffer&&t.buffer.textures[e]&&(t.gl.activeTexture(t.gl["TEXTURE"+i]),t.gl.bindTexture(t.gl.TEXTURE_2D,null))}})}},{key:"hasDepthTexture",value:function(){return this._hasDepthTexture}},{key:"getDepthTexture",value:function(){if(!this._hasDepthTexture)return null;var e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture)&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),!0)},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}},{key:"destroy",value:function(){if(this.allocated){var e=this.gl;this.buffer.textures.forEach((function(t){return e.deleteTexture(t)})),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}]),e}(),Kt=function(){function e(t){x(this,e),this.scene=t,this._renderBuffersBasic={},this._renderBuffersScaled={}}return C(e,[{key:"getRenderBuffer",value:function(e,t){var i=1===this.scene.canvas.resolutionScale?this._renderBuffersBasic:this._renderBuffersScaled,r=i[e];return r||(r=new Wt(this.scene.canvas.canvas,this.scene.canvas.gl,t),i[e]=r),r}},{key:"destroy",value:function(){for(var e in this._renderBuffersBasic)this._renderBuffersBasic[e].destroy();for(var t in this._renderBuffersScaled)this._renderBuffersScaled[t].destroy()}}]),e}();function Xt(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];var i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}var Yt=function(e,t){t=t||{};var i=new yt(e),r=e.canvas.canvas,s=e.canvas.gl,n=!!t.transparent,o=t.alphaDepthMask,a=new Q({}),l={},u={},A=[],c=[],h=!0,d=!0,p=!0,f=!0,v=!0,g=!0,m=!0,_=!0,y=new Kt(e),b=!1,w=new Ot(e),B=new jt(e);function x(){h&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e],i=t.drawableMap,r=t.drawableListPreCull,s=0;for(var n in i)i.hasOwnProperty(n)&&(r[s++]=i[n]);r.length=s}}(),h=!1,d=!0),d&&(!function(){for(var e in l)if(l.hasOwnProperty(e)){var t=l[e];t.isStateSortable&&(t.drawableListPreCull.sort(t.stateSortCompare),t.drawableList=t.drawableListPreCull)}var i=0;for(var r in l)if(l.hasOwnProperty(r))for(var s=l[r].drawableListPreCull,n=0,o=s.length;n0)for(i.withSAO=!0,I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||j>0||O>0||N>0){if(s.enable(s.CULL_FACE),s.enable(s.BLEND),n?(s.blendEquation(s.FUNC_ADD),s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA)):(s.blendEquation(s.FUNC_ADD),s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA)),i.backfaces=!1,o||s.depthMask(!1),(O>0||N>0)&&s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA),N>0)for(I=0;I0)for(I=0;I0)for(I=0;I0)for(I=0;I0||z>0){if(i.lastProgramId=null,e.highlightMaterial.glowThrough&&s.clear(s.DEPTH_BUFFER_BIT),z>0)for(I=0;I0)for(I=0;I0||K>0||G>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&s.clear(s.DEPTH_BUFFER_BIT),s.enable(s.BLEND),n?(s.blendEquation(s.FUNC_ADD),s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA)):s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA),s.enable(s.CULL_FACE),K>0)for(I=0;I0)for(I=0;I0||Y>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&s.clear(s.DEPTH_BUFFER_BIT),Y>0)for(I=0;I0)for(I=0;I0||Z>0){if(i.lastProgramId=null,e.selectedMaterial.glowThrough&&s.clear(s.DEPTH_BUFFER_BIT),s.enable(s.CULL_FACE),s.enable(s.BLEND),n?(s.blendEquation(s.FUNC_ADD),s.blendFuncSeparate(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA)):s.blendFunc(s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA),Z>0)for(I=0;I0)for(I=0;I1&&void 0!==arguments[1]?arguments[1]:o;p.reset(),x();var f=null,v=null;for(var g in p.pickSurface=h.pickSurface,h.canvasPos?(u[0]=h.canvasPos[0],u[1]=h.canvasPos[1],f=e.camera.viewMatrix,v=e.camera.projMatrix,p.canvasPos=h.canvasPos):(h.matrix?(f=h.matrix,v=e.camera.projMatrix):(A.set(h.origin||[0,0,0]),c.set(h.direction||[0,0,1]),d=$.addVec3(A,c,t),s[0]=Math.random(),s[1]=Math.random(),s[2]=Math.random(),$.normalizeVec3(s),$.cross3Vec3(c,s,n),f=$.lookAtMat4v(A,d,n,i),v=e.camera.ortho.matrix,p.origin=A,p.direction=c),u[0]=.5*r.clientWidth,u[1]=.5*r.clientHeight),l)if(l.hasOwnProperty(g))for(var m=l[g].drawableList,_=0,b=m.length;_4&&void 0!==arguments[4]?arguments[4]:E;if(!n&&!o)return this.pick({canvasPos:t,pickSurface:!0});var A=e.canvas.resolutionScale;i.reset(),i.backfaces=!0,i.frontface=!0,i.pickZNear=e.camera.project.near,i.pickZFar=e.camera.project.far,r=r||30;var c=y.getRenderBuffer("uniquePickColors-aabs",{depthTexture:!0,size:[2*r+1,2*r+1]});i.snapVectorA=[D(t[0]*A,s.drawingBufferWidth),S(t[1]*A,s.drawingBufferHeight)],i.snapInvVectorAB=[s.drawingBufferWidth/(2*r),s.drawingBufferHeight/(2*r)],c.bind(s.RGBA32I,s.RGBA32I,s.RGBA8UI),s.viewport(0,0,c.size[0],c.size[1]),s.enable(s.DEPTH_TEST),s.frontFace(s.CCW),s.disable(s.CULL_FACE),s.depthMask(!0),s.disable(s.BLEND),s.depthFunc(s.LEQUAL),s.clear(s.DEPTH_BUFFER_BIT),s.clearBufferiv(s.COLOR,0,new Int32Array([0,0,0,0])),s.clearBufferiv(s.COLOR,1,new Int32Array([0,0,0,0])),s.clearBufferuiv(s.COLOR,2,new Uint32Array([0,0,0,0]));var h=e.camera.viewMatrix,d=e.camera.projMatrix;for(var p in l)if(l.hasOwnProperty(p))for(var f=l[p].drawableList,v=0,g=f.length;v0){var j=Math.floor(H/4),G=c.size[0],z=j%G-Math.floor(G/2),W=Math.floor(j/G)-Math.floor(G/2),K=Math.sqrt(Math.pow(z,2)+Math.pow(W,2));V.push({x:z,y:W,dist:K,isVertex:n&&o?w[H+3]>b.length/2:n,result:[w[H+0],w[H+1],w[H+2],w[H+3]],normal:[B[H+0],B[H+1],B[H+2],B[H+3]],id:[x[H+0],x[H+1],x[H+2],x[H+3]]})}var X=null,Y=null,J=null,Z=null;if(V.length>0){V.sort((function(e,t){return e.isVertex!==t.isVertex?e.isVertex?-1:1:e.dist-t.dist})),Z=V[0].isVertex?"vertex":"edge";var q=V[0].result,ee=V[0].normal,te=V[0].id,ie=b[q[3]],re=ie.origin,se=ie.coordinateScale;Y=$.normalizeVec3([ee[0]/$.MAX_INT,ee[1]/$.MAX_INT,ee[2]/$.MAX_INT]),X=[q[0]*se[0]+re[0],q[1]*se[1]+re[1],q[2]*se[2]+re[2]],J=a.items[te[0]+(te[1]<<8)+(te[2]<<16)+(te[3]<<24)]}if(null===P&&null==X)return null;var ne=null;null!==X&&(ne=e.camera.projectWorldPos(X));var oe=J&&J.delegatePickedEntity?J.delegatePickedEntity():J;return u.reset(),u.snappedToEdge="edge"===Z,u.snappedToVertex="vertex"===Z,u.worldPos=X,u.worldNormal=Y,u.entity=oe,u.canvasPos=t,u.snappedCanvasPos=ne||t,u}),this.addMarker=function(t){this._occlusionTester=this._occlusionTester||new Rt(e,y),this._occlusionTester.addMarker(t),e.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){for(var e in x(),this._occlusionTester.bindRenderBuf(),i.reset(),i.backfaces=!0,i.frontface=!0,s.viewport(0,0,s.drawingBufferWidth,s.drawingBufferHeight),s.clearColor(0,0,0,0),s.enable(s.DEPTH_TEST),s.disable(s.CULL_FACE),s.disable(s.BLEND),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),l)if(l.hasOwnProperty(e))for(var t=l[e].drawableList,r=0,n=t.length;r0&&void 0!==arguments[0]?arguments[0]:{},t=y.getRenderBuffer("snapshot");e.width&&e.height&&t.setSize([e.width,e.height]),t.bind(),t.clear(),b=!0},this.renderSnapshot=function(){b&&(y.getRenderBuffer("snapshot").clear(),this.render({force:!0,opaqueOnly:!1}),p=!0)},this.readSnapshot=function(e){return y.getRenderBuffer("snapshot").readImage(e)},this.readSnapshotAsCanvas=function(){return y.getRenderBuffer("snapshot").readImageAsCanvas()},this.endSnapshot=function(){b&&(y.getRenderBuffer("snapshot").unbind(),b=!1)},this.destroy=function(){l={},u={},y.destroy(),w.destroy(),B.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}},Jt=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).KEY_BACKSPACE=8,r.KEY_TAB=9,r.KEY_ENTER=13,r.KEY_SHIFT=16,r.KEY_CTRL=17,r.KEY_ALT=18,r.KEY_PAUSE_BREAK=19,r.KEY_CAPS_LOCK=20,r.KEY_ESCAPE=27,r.KEY_PAGE_UP=33,r.KEY_PAGE_DOWN=34,r.KEY_END=35,r.KEY_HOME=36,r.KEY_LEFT_ARROW=37,r.KEY_UP_ARROW=38,r.KEY_RIGHT_ARROW=39,r.KEY_DOWN_ARROW=40,r.KEY_INSERT=45,r.KEY_DELETE=46,r.KEY_NUM_0=48,r.KEY_NUM_1=49,r.KEY_NUM_2=50,r.KEY_NUM_3=51,r.KEY_NUM_4=52,r.KEY_NUM_5=53,r.KEY_NUM_6=54,r.KEY_NUM_7=55,r.KEY_NUM_8=56,r.KEY_NUM_9=57,r.KEY_A=65,r.KEY_B=66,r.KEY_C=67,r.KEY_D=68,r.KEY_E=69,r.KEY_F=70,r.KEY_G=71,r.KEY_H=72,r.KEY_I=73,r.KEY_J=74,r.KEY_K=75,r.KEY_L=76,r.KEY_M=77,r.KEY_N=78,r.KEY_O=79,r.KEY_P=80,r.KEY_Q=81,r.KEY_R=82,r.KEY_S=83,r.KEY_T=84,r.KEY_U=85,r.KEY_V=86,r.KEY_W=87,r.KEY_X=88,r.KEY_Y=89,r.KEY_Z=90,r.KEY_LEFT_WINDOW=91,r.KEY_RIGHT_WINDOW=92,r.KEY_SELECT_KEY=93,r.KEY_NUMPAD_0=96,r.KEY_NUMPAD_1=97,r.KEY_NUMPAD_2=98,r.KEY_NUMPAD_3=99,r.KEY_NUMPAD_4=100,r.KEY_NUMPAD_5=101,r.KEY_NUMPAD_6=102,r.KEY_NUMPAD_7=103,r.KEY_NUMPAD_8=104,r.KEY_NUMPAD_9=105,r.KEY_MULTIPLY=106,r.KEY_ADD=107,r.KEY_SUBTRACT=109,r.KEY_DECIMAL_POINT=110,r.KEY_DIVIDE=111,r.KEY_F1=112,r.KEY_F2=113,r.KEY_F3=114,r.KEY_F4=115,r.KEY_F5=116,r.KEY_F6=117,r.KEY_F7=118,r.KEY_F8=119,r.KEY_F9=120,r.KEY_F10=121,r.KEY_F11=122,r.KEY_F12=123,r.KEY_NUM_LOCK=144,r.KEY_SCROLL_LOCK=145,r.KEY_SEMI_COLON=186,r.KEY_EQUAL_SIGN=187,r.KEY_COMMA=188,r.KEY_DASH=189,r.KEY_PERIOD=190,r.KEY_FORWARD_SLASH=191,r.KEY_GRAVE_ACCENT=192,r.KEY_OPEN_BRACKET=219,r.KEY_BACK_SLASH=220,r.KEY_CLOSE_BRACKET=221,r.KEY_SINGLE_QUOTE=222,r.KEY_SPACE=32,r.element=s.element,r.altDown=!1,r.ctrlDown=!1,r.mouseDownLeft=!1,r.mouseDownMiddle=!1,r.mouseDownRight=!1,r.keyDown=[],r.enabled=!0,r.keyboardEnabled=!0,r.mouseover=!1,r.mouseCanvasPos=$.vec2(),r._keyboardEventsElement=s.keyboardEventsElement||document,r._bindEvents(),r}return C(i,[{key:"_bindEvents",value:function(){var e=this;if(!this._eventsBound){this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!0:t.keyCode===e.KEY_ALT?e.altDown=!0:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!0),e.keyDown[t.keyCode]=!0,e.fire("keydown",t.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=function(t){e.enabled&&e.keyboardEnabled&&"INPUT"!==t.target.tagName&&"TEXTAREA"!==t.target.tagName&&(t.keyCode===e.KEY_CTRL?e.ctrlDown=!1:t.keyCode===e.KEY_ALT?e.altDown=!1:t.keyCode===e.KEY_SHIFT&&(e.shiftDown=!1),e.keyDown[t.keyCode]=!1,e.fire("keyup",t.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=function(t){e.enabled&&(e.mouseover=!0,e._getMouseCanvasPos(t),e.fire("mouseenter",e.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=function(t){e.enabled&&(e.mouseover=!1,e._getMouseCanvasPos(t),e.fire("mouseleave",e.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!0;break;case 2:e.mouseDownMiddle=!0;break;case 3:e.mouseDownRight=!0}e._getMouseCanvasPos(t),e.element.focus(),e.fire("mousedown",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=function(t){if(e.enabled){switch(t.which){case 1:e.mouseDownLeft=!1;break;case 2:e.mouseDownMiddle=!1;break;case 3:e.mouseDownRight=!1}e.fire("mouseup",e.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("click",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=function(t){if(e.enabled){switch(t.which){case 1:case 3:e.mouseDownLeft=!1,e.mouseDownRight=!1;break;case 2:e.mouseDownMiddle=!1}e._getMouseCanvasPos(t),e.fire("dblclick",e.mouseCanvasPos,!0),e.mouseover&&t.preventDefault()}});var t=this.scene.tickify((function(){return e.fire("mousemove",e.mouseCanvasPos,!0)}));this.element.addEventListener("mousemove",this._mouseMoveListener=function(i){e.enabled&&(e._getMouseCanvasPos(i),t(),e.mouseover&&i.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=function(t){e.enabled&&(e._getMouseCanvasPos(t),e.fire("contextmenu",e.mouseCanvasPos,!0))});var i=this.scene.tickify((function(t){e.fire("mousewheel",t,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=function(t,r){if(e.enabled){var s=Math.max(-1,Math.min(1,40*-t.deltaY));i(s)}},{passive:!0});var r,s;this.on("mousedown",(function(e){r=e[0],s=e[1]})),this.on("mouseup",(function(t){r>=t[0]-2&&r<=t[0]+2&&s>=t[1]-2&&s<=t[1]+2&&e.fire("mouseclicked",t,!0)})),this.element.addEventListener("touchstart",this._touchstartListener=function(t){e.enabled&&A(t.changedTouches).forEach((function(t){e.fire("touchstart",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=function(t){e.enabled&&A(t.changedTouches).forEach((function(t){e.fire("touchend",[t.identifier,e._getTouchCanvasPos(t)],!0)}))}),this._eventsBound=!0}}},{key:"_unbindEvents",value:function(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}},{key:"_getTouchCanvasPos",value:function(e){for(var t=e.target,i=0,r=0;t.offsetParent;)i+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-r]}},{key:"_getMouseCanvasPos",value:function(e){if(e){for(var t=e.target,i=0,r=0;t.offsetParent;)i+=t.offsetLeft,r+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-r}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}},{key:"setEnabled",value:function(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}},{key:"getEnabled",value:function(){return this.enabled}},{key:"setKeyboardEnabled",value:function(e){this.keyboardEnabled=e}},{key:"getKeyboardEnabled",value:function(){return this.keyboardEnabled}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._unbindEvents()}}]),i}(),Zt=new Q({}),qt=function(){function e(t){for(var i in x(this,e),this.id=Zt.addItem({}),t)t.hasOwnProperty(i)&&(this[i]=t[i])}return C(e,[{key:"destroy",value:function(){Zt.removeItem(this.id)}}]),e}(),$t=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({boundary:[0,0,100,100]}),r.boundary=s.boundary,r.autoBoundary=s.autoBoundary,r}return C(i,[{key:"type",get:function(){return"Viewport"}},{key:"boundary",get:function(){return this._state.boundary},set:function(e){if(!this._autoBoundary){if(!e){var t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}},{key:"autoBoundary",get:function(){return this._autoBoundary},set:function(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){var t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),ei=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).camera=e,r._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r._fov=60,r._canvasResized=r.scene.canvas.on("boundary",r._needUpdate,b(r)),r.fov=s.fov,r.fovAxis=s.fovAxis,r.near=s.near,r.far=s.far,r}return C(i,[{key:"type",get:function(){return"Perspective"}},{key:"_update",value:function(){var e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis,r=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(r/=t),r=Math.min(r,120),$.perspectiveMat4(r*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}},{key:"fov",get:function(){return this._fov},set:function(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}},{key:"fovAxis",get:function(){return this._fovAxis},set:function(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,s){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,r),$.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,r,s),s}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}]),i}(),ti=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).camera=e,r._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.scale=s.scale,r.near=s.near,r.far=s.far,r._onCanvasBoundary=r.scene.canvas.on("boundary",r._needUpdate,b(r)),r}return C(i,[{key:"type",get:function(){return"Ortho"}},{key:"_update",value:function(){var e,t,i,r,s=this.scene,n=.5*this._scale,o=s.canvas.boundary,a=o[2],l=o[3],u=a/l;a>l?(e=-n,t=n,i=n/u,r=-n/u):(e=-n*u,t=n*u,i=n,r=-n),$.orthoMat4c(e,t,r,i,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}},{key:"near",get:function(){return this._state.near},set:function(e){var t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}},{key:"far",get:function(){return this._state.far},set:function(e){var t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,s){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,r),$.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,r,s),s}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}]),i}(),ii=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).camera=e,r._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4(),near:.1,far:1e4}),r._left=-1,r._right=1,r._bottom=-1,r._top=1,r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!0,r.left=s.left,r.right=s.right,r.bottom=s.bottom,r.top=s.top,r.near=s.near,r.far=s.far,r}return C(i,[{key:"type",get:function(){return"Frustum"}},{key:"_update",value:function(){$.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"left",get:function(){return this._left},set:function(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}},{key:"right",get:function(){return this._right},set:function(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}},{key:"top",get:function(){return this._top},set:function(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}},{key:"bottom",get:function(){return this._bottom},set:function(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}},{key:"near",get:function(){return this._state.near},set:function(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}},{key:"far",get:function(){return this._state.far},set:function(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,s){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,r),$.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,r,s),s}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),ri=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).camera=e,r._state=new qt({matrix:$.mat4(),inverseMatrix:$.mat4(),transposedMatrix:$.mat4()}),r._inverseMatrixDirty=!0,r._transposedMatrixDirty=!1,r.matrix=s.matrix,r}return C(i,[{key:"type",get:function(){return"CustomProjection"}},{key:"matrix",get:function(){return this._state.matrix},set:function(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}},{key:"inverseMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&($.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}},{key:"transposedMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&($.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}},{key:"unproject",value:function(e,t,i,r,s){var n=this.scene.canvas.canvas,o=n.offsetWidth/2,a=n.offsetHeight/2;return i[0]=(e[0]-o)/o,i[1]=(e[1]-a)/a,i[2]=t,i[3]=1,$.mulMat4v4(this.inverseMatrix,i,r),$.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1,$.mulMat4v4(this.camera.inverseViewMatrix,r,s),s}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),si=$.vec3(),ni=$.vec3(),oi=$.vec3(),ai=$.vec3(),li=$.vec3(),ui=$.vec3(),Ai=$.vec4(),ci=$.vec4(),hi=$.vec4(),di=$.mat4(),pi=$.mat4(),fi=$.vec3(),vi=$.vec3(),gi=$.vec3(),mi=$.vec3(),_i=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({deviceMatrix:$.mat4(),hasDeviceMatrix:!1,matrix:$.mat4(),normalMatrix:$.mat4(),inverseMatrix:$.mat4()}),r._perspective=new ei(b(r)),r._ortho=new ti(b(r)),r._frustum=new ii(b(r)),r._customProjection=new ri(b(r)),r._project=r._perspective,r._eye=$.vec3([0,0,10]),r._look=$.vec3([0,0,0]),r._up=$.vec3([0,1,0]),r._worldUp=$.vec3([0,1,0]),r._worldRight=$.vec3([1,0,0]),r._worldForward=$.vec3([0,0,-1]),r.deviceMatrix=s.deviceMatrix,r.eye=s.eye,r.look=s.look,r.up=s.up,r.worldAxis=s.worldAxis,r.gimbalLock=s.gimbalLock,r.constrainPitch=s.constrainPitch,r.projection=s.projection,r._perspective.on("matrix",(function(){"perspective"===r._projectionType&&r.fire("projMatrix",r._perspective.matrix)})),r._ortho.on("matrix",(function(){"ortho"===r._projectionType&&r.fire("projMatrix",r._ortho.matrix)})),r._frustum.on("matrix",(function(){"frustum"===r._projectionType&&r.fire("projMatrix",r._frustum.matrix)})),r._customProjection.on("matrix",(function(){"customProjection"===r._projectionType&&r.fire("projMatrix",r._customProjection.matrix)})),r}return C(i,[{key:"type",get:function(){return"Camera"}},{key:"_update",value:function(){var e,t=this._state;"ortho"===this.projection?($.subVec3(this._eye,this._look,fi),$.normalizeVec3(fi,vi),$.mulVec3Scalar(vi,1e3,gi),$.addVec3(this._look,gi,mi),e=mi):e=this._eye,t.hasDeviceMatrix?($.lookAtMat4v(e,this._look,this._up,pi),$.mulMat4(t.deviceMatrix,pi,t.matrix)):$.lookAtMat4v(e,this._look,this._up,t.matrix),$.inverseMat4(this._state.matrix,this._state.inverseMatrix),$.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}},{key:"orbitYaw",value:function(e){var t=$.subVec3(this._eye,this._look,si);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,di),t=$.transformPoint3(di,t,ni),this.eye=$.addVec3(this._look,t,oi),this.up=$.transformPoint3(di,this._up,ai)}},{key:"orbitPitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._eye,this._look,si),i=$.cross3Vec3($.normalizeVec3(t,ni),$.normalizeVec3(this._up,oi));$.rotationMat4v(.0174532925*e,i,di),t=$.transformPoint3(di,t,ai),this.up=$.transformPoint3(di,this._up,li),this.eye=$.addVec3(t,this._look,ui)}}},{key:"yaw",value:function(e){var t=$.subVec3(this._look,this._eye,si);$.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,di),t=$.transformPoint3(di,t,ni),this.look=$.addVec3(t,this._eye,oi),this._gimbalLock&&(this.up=$.transformPoint3(di,this._up,ai))}},{key:"pitch",value:function(e){if(!(this._constrainPitch&&(e=$.dotVec3(this._up,this._worldUp)/$.DEGTORAD)<1)){var t=$.subVec3(this._look,this._eye,si),i=$.cross3Vec3($.normalizeVec3(t,ni),$.normalizeVec3(this._up,oi));$.rotationMat4v(.0174532925*e,i,di),this.up=$.transformPoint3(di,this._up,ui),t=$.transformPoint3(di,t,ai),this.look=$.addVec3(t,this._eye,li)}}},{key:"pan",value:function(e){var t,i=$.subVec3(this._eye,this._look,si),r=[0,0,0];if(0!==e[0]){var s=$.cross3Vec3($.normalizeVec3(i,[]),$.normalizeVec3(this._up,ni));t=$.mulVec3Scalar(s,e[0]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]}0!==e[1]&&(t=$.mulVec3Scalar($.normalizeVec3(this._up,oi),e[1]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),0!==e[2]&&(t=$.mulVec3Scalar($.normalizeVec3(i,ai),e[2]),r[0]+=t[0],r[1]+=t[1],r[2]+=t[2]),this.eye=$.addVec3(this._eye,r,li),this.look=$.addVec3(this._look,r,ui)}},{key:"zoom",value:function(e){var t=$.subVec3(this._eye,this._look,si),i=Math.abs($.lenVec3(t,ni)),r=Math.abs(i+e);if(!(r<.5)){var s=$.normalizeVec3(t,oi);this.eye=$.addVec3(this._look,$.mulVec3Scalar(s,r),ai)}}},{key:"eye",get:function(){return this._eye},set:function(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}},{key:"look",get:function(){return this._look},set:function(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}},{key:"up",get:function(){return this._up},set:function(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}},{key:"deviceMatrix",get:function(){return this._state.deviceMatrix},set:function(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}},{key:"worldAxis",get:function(){return this._worldAxis},set:function(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=$.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}},{key:"worldUp",get:function(){return this._worldUp}},{key:"xUp",get:function(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}},{key:"yUp",get:function(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}},{key:"zUp",get:function(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}},{key:"worldRight",get:function(){return this._worldRight}},{key:"worldForward",get:function(){return this._worldForward}},{key:"gimbalLock",get:function(){return this._gimbalLock},set:function(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}},{key:"constrainPitch",set:function(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}},{key:"eyeLookDist",get:function(){return $.lenVec3($.subVec3(this._look,this._eye,si))}},{key:"matrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"viewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}},{key:"normalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"viewNormalMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}},{key:"inverseViewMatrix",get:function(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}},{key:"projMatrix",get:function(){return this[this.projection].matrix}},{key:"perspective",get:function(){return this._perspective}},{key:"ortho",get:function(){return this._ortho}},{key:"frustum",get:function(){return this._frustum}},{key:"customProjection",get:function(){return this._customProjection}},{key:"projection",get:function(){return this._projectionType},set:function(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}},{key:"project",get:function(){return this._project}},{key:"projectWorldPos",value:function(e){var t=Ai,i=ci,r=hi;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,$.mulMat4v4(this.viewMatrix,t,i),$.mulMat4v4(this.projMatrix,i,r),$.mulVec3Scalar(r,1/r[3]),r[3]=1,r[1]*=-1;var s=this.scene.canvas.canvas,n=s.offsetWidth/2,o=s.offsetHeight/2;return[r[0]*n+n,r[1]*o+o]}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),yi=function(e){g(i,we);var t=_(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),t.call(this,e,r)}return C(i,[{key:"type",get:function(){return"Light"}},{key:"isLight",get:function(){return!0}}]),i}(),bi=function(e){g(i,yi);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s))._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var n=r.scene.camera,o=r.scene.canvas;return r._onCameraViewMatrix=n.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=n.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=o.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new qt({type:"dir",dir:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,space:s.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(r._shadowViewMatrixDirty){r._shadowViewMatrix||(r._shadowViewMatrix=$.identityMat4());var e=r.scene.camera,t=r._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]];$.lookAtMat4v(s,i,[0,1,0],r._shadowViewMatrix),r._shadowViewMatrixDirty=!1}return r._shadowViewMatrix},getShadowProjMatrix:function(){return r._shadowProjMatrixDirty&&(r._shadowProjMatrix||(r._shadowProjMatrix=$.identityMat4()),$.orthoMat4c(-40,40,-40,40,-40,80,r._shadowProjMatrix),r._shadowProjMatrixDirty=!1),r._shadowProjMatrix},getShadowRenderBuf:function(){return r._shadowRenderBuf||(r._shadowRenderBuf=new Wt(r.scene.canvas.canvas,r.scene.canvas.gl,{size:[1024,1024]})),r._shadowRenderBuf}}),r.dir=s.dir,r.color=s.color,r.intensity=s.intensity,r.castsShadow=s.castsShadow,r.scene._lightCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"DirLight"}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}(),wi=function(e){g(i,yi);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state={type:"ambient",color:$.vec3([.7,.7,.7]),intensity:1},r.color=s.color,r.intensity=s.intensity,r.scene._lightCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"AmbientLight"}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._lightDestroyed(this)}}]),i}(),Bi=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),r=t.call(this,e,s),re.memory.meshes++,r}return C(i,[{key:"type",get:function(){return"Geometry"}},{key:"isGeometry",get:function(){return!0}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),re.memory.meshes--}}]),i}(),xi=function(){var e=[],t=[],i=[],r=[],s=[],n=0,o=new Uint16Array(3),a=new Uint16Array(3),l=new Uint16Array(3),u=$.vec3(),A=$.vec3(),c=$.vec3(),h=$.vec3(),d=$.vec3(),p=$.vec3(),f=$.vec3();return function(v,g,m,_){!function(s,n){var o,a,l,u,A,c,h={},d=Math.pow(10,4),p=0;for(A=0,c=s.length;AI)||(E=i[P.index1],F=i[P.index2],(!S&&E>65535||F>65535)&&(S=!0),k.push(E),k.push(F));return S?new Uint32Array(k):new Uint16Array(k)}}();var Pi=function(){var e=$.mat4(),t=$.mat4();return function(i,r){r=r||$.mat4();var s=i[0],n=i[1],o=i[2],a=i[3]-s,l=i[4]-n,u=i[5]-o,A=65535;return $.identityMat4(e),$.translationMat4v(i,e),$.identityMat4(t),$.scalingMat4v([a/A,l/A,u/A],t),$.mulMat4(e,t,r),r}}(),Ci=function(){var e=$.mat4(),t=$.mat4();return function(i,r,s){var n,o=new Uint16Array(i.length),a=new Float32Array([s[0]!==r[0]?65535/(s[0]-r[0]):0,s[1]!==r[1]?65535/(s[1]-r[1]):0,s[2]!==r[2]?65535/(s[2]-r[2]):0]);for(n=0;n=0?1:-1),a=(1-Math.abs(s))*(n>=0?1:-1);s=o,n=a}return new Int8Array([Math[i](127.5*s+(s<0?-1:0)),Math[r](127.5*n+(n<0?-1:0))])}function Fi(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var r=1-Math.abs(t)-Math.abs(i);r<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var s=Math.sqrt(t*t+i*i+r*r);return[t/s,i/s,r/s]}function ki(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}var Ii={getPositionsBounds:function(e){var t,i,r=new Float32Array(3),s=new Float32Array(3);for(t=0;t<3;t++)r[t]=Number.MAX_VALUE,s[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,s=e.length;r2&&void 0!==arguments[2]?arguments[2]:e;return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){var t,i,r=new Float32Array(2),s=new Float32Array(2);for(t=0;t<2;t++)r[t]=Number.MAX_VALUE,s[t]=-Number.MAX_VALUE;for(t=0;t2&&void 0!==arguments[2]?arguments[2]:new Float32Array(e.length),r=0,s=e.length;rs&&(i=t,s=r),(r=ki(e,o,Fi(t=Ei(e,o,"floor","ceil"))))>s&&(i=t,s=r),(r=ki(e,o,Fi(t=Ei(e,o,"ceil","ceil"))))>s&&(i=t,s=r),n[o]=i[0],n[o+1]=i[1];return n},decompressNormals:function(e,t){for(var i=0,r=0,s=e.length;i=0?1:-1),o=(1-Math.abs(n))*(o>=0?1:-1));var l=Math.sqrt(n*n+o*o+a*a);t[r+0]=n/l,t[r+1]=o/l,t[r+2]=a/l,r+=3}return t},decompressNormal:function(e,t){var i=e[0],r=e[1];i=(2*i+1)/255,r=(2*r+1)/255;var s=1-Math.abs(i)-Math.abs(r);s<0&&(i=(1-Math.abs(r))*(i>=0?1:-1),r=(1-Math.abs(i))*(r>=0?1:-1));var n=Math.sqrt(i*i+r*r+s*s);return t[0]=i/n,t[1]=r/n,t[2]=s/n,t}},Di=re.memory,Si=$.AABB3(),Ti=function(e){g(i,Bi);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s))._state=new qt({compressGeometry:!!s.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=s.edgeThreshold||10,r._edgeIndicesBuf=null,r._pickTrianglePositionsBuf=null,r._pickTriangleColorsBuf=null,r._aabbDirty=!0,r._boundingSphere=!0,r._aabb=null,r._aabbDirty=!0,r._obb=null,r._obbDirty=!0;var n=r._state,o=r.scene.canvas.gl;switch(s.primitive=s.primitive||"triangles",s.primitive){case"points":n.primitive=o.POINTS,n.primitiveName=s.primitive;break;case"lines":n.primitive=o.LINES,n.primitiveName=s.primitive;break;case"line-loop":n.primitive=o.LINE_LOOP,n.primitiveName=s.primitive;break;case"line-strip":n.primitive=o.LINE_STRIP,n.primitiveName=s.primitive;break;case"triangles":n.primitive=o.TRIANGLES,n.primitiveName=s.primitive;break;case"triangle-strip":n.primitive=o.TRIANGLE_STRIP,n.primitiveName=s.primitive;break;case"triangle-fan":n.primitive=o.TRIANGLE_FAN,n.primitiveName=s.primitive;break;default:r.error("Unsupported value for 'primitive': '"+s.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),n.primitive=o.TRIANGLES,n.primitiveName=s.primitive}if(s.positions)if(r._state.compressGeometry){var a=Ii.getPositionsBounds(s.positions),l=Ii.compressPositions(s.positions,a.min,a.max);n.positions=l.quantized,n.positionsDecodeMatrix=l.decodeMatrix}else n.positions=s.positions.constructor===Float32Array?s.positions:new Float32Array(s.positions);if(s.colors&&(n.colors=s.colors.constructor===Float32Array?s.colors:new Float32Array(s.colors)),s.uv)if(r._state.compressGeometry){var u=Ii.getUVBounds(s.uv),A=Ii.compressUVs(s.uv,u.min,u.max);n.uv=A.quantized,n.uvDecodeMatrix=A.decodeMatrix}else n.uv=s.uv.constructor===Float32Array?s.uv:new Float32Array(s.uv);return s.normals&&(r._state.compressGeometry?n.normals=Ii.compressNormals(s.normals):n.normals=s.normals.constructor===Float32Array?s.normals:new Float32Array(s.normals)),s.indices&&(n.indices=s.indices.constructor===Uint32Array||s.indices.constructor===Uint16Array?s.indices:new Uint32Array(s.indices),"triangles"===r._state.primitiveName&&(r._numTriangles=s.indices.length/3)),r._buildHash(),Di.meshes++,r._buildVBOs(),r}return C(i,[{key:"type",get:function(){return"ReadableGeometry"}},{key:"isReadableGeometry",get:function(){return!0}},{key:"_buildVBOs",value:function(){var e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),Di.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),Di.positions+=e.positionsBuf.numItems),e.normals){var i=e.compressGeometry;e.normalsBuf=new Dt(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),Di.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),Di.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new Dt(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),Di.uvs+=e.uvBuf.numItems)}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}},{key:"_getPickTrianglePositions",value:function(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}},{key:"_getPickTriangleColors",value:function(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}},{key:"_buildEdgeIndices",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=xi(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),Di.indices+=this._edgeIndicesBuf.numItems}}},{key:"_buildPickTriangleVBOs",value:function(){var e=this._state;if(e.positions&&e.indices){var t=this.scene.canvas.gl,i=$.buildPickTriangles(e.positions,e.indices,e.compressGeometry),r=i.positions,s=i.colors;this._pickTrianglePositionsBuf=new Dt(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new Dt(t,t.ARRAY_BUFFER,s,s.length,4,t.STATIC_DRAW,!0),Di.positions+=this._pickTrianglePositionsBuf.numItems,Di.colors+=this._pickTriangleColorsBuf.numItems}}},{key:"_buildPickVertexVBOs",value:function(){}},{key:"_webglContextLost",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}},{key:"_webglContextRestored",value:function(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"compressGeometry",get:function(){return this._state.compressGeometry}},{key:"positions",get:function(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Ii.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null},set:function(e){var t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){var r=Ii.getPositionsBounds(e),s=Ii.compressPositions(e,r.min,r.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}},{key:"normals",get:function(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){var e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Ii.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry normals - quantized geometry is immutable");else{var t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}}},{key:"uv",get:function(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Ii.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry UVs - quantized geometry is immutable");else{var t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}}},{key:"colors",get:function(){return this._state.colors},set:function(e){if(this._state.compressGeometry)this.error("can't update geometry colors - quantized geometry is immutable");else{var t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}}},{key:"indices",get:function(){return this._state.indices}},{key:"aabb",get:function(){return this._aabbDirty&&(this._aabb||(this._aabb=$.AABB3()),$.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}},{key:"obb",get:function(){return this._obbDirty&&(this._obb||(this._obb=$.OBB3()),$.positions3ToAABB3(this._state.positions,Si,this._state.positionsDecodeMatrix),$.AABB3ToOBB3(Si,this._obb),this._obbDirty=!1),this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_setAABBDirty",value:function(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),Di.meshes--}}]),i}();function Li(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var s=e.center,n=s?s[0]:0,o=s?s[1]:0,a=s?s[2]:0,l=-t+n,u=-i+o,A=-r+a,c=t+n,h=i+o,d=r+a;return le.apply(e,{positions:[c,h,d,l,h,d,l,u,d,c,u,d,c,h,d,c,u,d,c,u,A,c,h,A,c,h,d,c,h,A,l,h,A,l,h,d,l,h,d,l,h,A,l,u,A,l,u,d,l,u,A,c,u,A,c,u,d,l,u,d,c,u,A,l,u,A,l,h,A,c,h,A],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}var Ri=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),r=t.call(this,e,s),re.memory.materials++,r}return C(i,[{key:"type",get:function(){return"Material"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),re.memory.materials--}}]),i}(),Ui={opaque:0,mask:1,blend:2},Oi=["opaque","mask","blend"],Ni=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"PhongMaterial",ambient:$.vec3([1,1,1]),diffuse:$.vec3([1,1,1]),specular:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.ambient=s.ambient,r.diffuse=s.diffuse,r.specular=s.specular,r.emissive=s.emissive,r.alpha=s.alpha,r.shininess=s.shininess,r.reflectivity=s.reflectivity,r.lineWidth=s.lineWidth,r.pointSize=s.pointSize,s.ambientMap&&(r._ambientMap=r._checkComponent("Texture",s.ambientMap)),s.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",s.diffuseMap)),s.specularMap&&(r._specularMap=r._checkComponent("Texture",s.specularMap)),s.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",s.emissiveMap)),s.alphaMap&&(r._alphaMap=r._checkComponent("Texture",s.alphaMap)),s.reflectivityMap&&(r._reflectivityMap=r._checkComponent("Texture",s.reflectivityMap)),s.normalMap&&(r._normalMap=r._checkComponent("Texture",s.normalMap)),s.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",s.occlusionMap)),s.diffuseFresnel&&(r._diffuseFresnel=r._checkComponent("Fresnel",s.diffuseFresnel)),s.specularFresnel&&(r._specularFresnel=r._checkComponent("Fresnel",s.specularFresnel)),s.emissiveFresnel&&(r._emissiveFresnel=r._checkComponent("Fresnel",s.emissiveFresnel)),s.alphaFresnel&&(r._alphaFresnel=r._checkComponent("Fresnel",s.alphaFresnel)),s.reflectivityFresnel&&(r._reflectivityFresnel=r._checkComponent("Fresnel",s.reflectivityFresnel)),r.alphaMode=s.alphaMode,r.alphaCutoff=s.alphaCutoff,r.backfaces=s.backfaces,r.frontface=s.frontface,r._makeHash(),r}return C(i,[{key:"type",get:function(){return"PhongMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"shininess",get:function(){return this._state.shininess},set:function(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"reflectivity",get:function(){return this._state.reflectivity},set:function(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}},{key:"normalMap",get:function(){return this._normalMap}},{key:"ambientMap",get:function(){return this._ambientMap}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specularMap",get:function(){return this._specularMap}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"reflectivityMap",get:function(){return this._reflectivityMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"diffuseFresnel",get:function(){return this._diffuseFresnel}},{key:"specularFresnel",get:function(){return this._specularFresnel}},{key:"emissiveFresnel",get:function(){return this._emissiveFresnel}},{key:"alphaFresnel",get:function(){return this._alphaFresnel}},{key:"reflectivityFresnel",get:function(){return this._reflectivityFresnel}},{key:"alphaMode",get:function(){return Oi[this._state.alphaMode]},set:function(e){var t=Ui[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Qi={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}},Vi=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),r._preset="default",s.preset?(r.preset=s.preset,void 0!==s.fill&&(r.fill=s.fill),s.fillColor&&(r.fillColor=s.fillColor),void 0!==s.fillAlpha&&(r.fillAlpha=s.fillAlpha),void 0!==s.edges&&(r.edges=s.edges),s.edgeColor&&(r.edgeColor=s.edgeColor),void 0!==s.edgeAlpha&&(r.edgeAlpha=s.edgeAlpha),void 0!==s.edgeWidth&&(r.edgeWidth=s.edgeWidth),void 0!==s.backfaces&&(r.backfaces=s.backfaces),void 0!==s.glowThrough&&(r.glowThrough=s.glowThrough)):(r.fill=s.fill,r.fillColor=s.fillColor,r.fillAlpha=s.fillAlpha,r.edges=s.edges,r.edgeColor=s.edgeColor,r.edgeAlpha=s.edgeAlpha,r.edgeWidth=s.edgeWidth,r.backfaces=s.backfaces,r.glowThrough=s.glowThrough),r}return C(i,[{key:"type",get:function(){return"EmphasisMaterial"}},{key:"presets",get:function(){return Qi}},{key:"fill",get:function(){return this._state.fill},set:function(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}},{key:"fillColor",get:function(){return this._state.fillColor},set:function(e){var t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}},{key:"fillAlpha",get:function(){return this._state.fillAlpha},set:function(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"glowThrough",get:function(){return this._state.glowThrough},set:function(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Qi[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Qi).join(", "))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Hi={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}},ji=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),r._preset="default",s.preset?(r.preset=s.preset,s.edgeColor&&(r.edgeColor=s.edgeColor),void 0!==s.edgeAlpha&&(r.edgeAlpha=s.edgeAlpha),void 0!==s.edgeWidth&&(r.edgeWidth=s.edgeWidth)):(r.edgeColor=s.edgeColor,r.edgeAlpha=s.edgeAlpha,r.edgeWidth=s.edgeWidth),r.edges=!1!==s.edges,r}return C(i,[{key:"type",get:function(){return"EdgeMaterial"}},{key:"presets",get:function(){return Hi}},{key:"edges",get:function(){return this._state.edges},set:function(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){var t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"edgeAlpha",get:function(){return this._state.edgeAlpha},set:function(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}},{key:"edgeWidth",get:function(){return this._state.edgeWidth},set:function(e){this._state.edgeWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Hi[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Hi).join(", "))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Gi={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}},zi=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._units="meters",r._scale=1,r._origin=$.vec3([0,0,0]),r.units=s.units,r.scale=s.scale,r.origin=s.origin,r}return C(i,[{key:"unitsInfo",get:function(){return Gi}},{key:"units",get:function(){return this._units},set:function(e){e||(e="meters"),Gi[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}},{key:"scale",get:function(){return this._scale},set:function(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}},{key:"origin",get:function(){return this._origin},set:function(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}},{key:"worldToRealPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}},{key:"realToWorldPos",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:$.vec3(3);return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}]),i}(),Wi=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._supported=bt.SUPPORTED_EXTENSIONS.OES_standard_derivatives,r.enabled=s.enabled,r.kernelRadius=s.kernelRadius,r.intensity=s.intensity,r.bias=s.bias,r.scale=s.scale,r.minResolution=s.minResolution,r.numSamples=s.numSamples,r.blur=s.blur,r.blendCutoff=s.blendCutoff,r.blendFactor=s.blendFactor,r}return C(i,[{key:"supported",get:function(){return this._supported}},{key:"enabled",get:function(){return this._enabled},set:function(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}},{key:"possible",get:function(){if(!this._supported)return!1;if(!this._enabled)return!1;var e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}},{key:"active",get:function(){return this._active}},{key:"kernelRadius",get:function(){return this._kernelRadius},set:function(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}},{key:"intensity",get:function(){return this._intensity},set:function(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}},{key:"bias",get:function(){return this._bias},set:function(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}},{key:"scale",get:function(){return this._scale},set:function(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}},{key:"minResolution",get:function(){return this._minResolution},set:function(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}},{key:"numSamples",get:function(){return this._numSamples},set:function(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}},{key:"blur",get:function(){return this._blur},set:function(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}},{key:"blendCutoff",get:function(){return this._blendCutoff},set:function(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}},{key:"blendFactor",get:function(){return this._blendFactor},set:function(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Ki=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).sliceColor=s.sliceColor,r.sliceThickness=s.sliceThickness,r}return C(i,[{key:"sliceThickness",get:function(){return this._sliceThickness},set:function(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}},{key:"sliceColor",get:function(){return this._sliceColor},set:function(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Xi={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}},Yi=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),s.preset?(r.preset=s.preset,void 0!==s.pointSize&&(r.pointSize=s.pointSize),void 0!==s.roundPoints&&(r.roundPoints=s.roundPoints),void 0!==s.perspectivePoints&&(r.perspectivePoints=s.perspectivePoints),void 0!==s.minPerspectivePointSize&&(r.minPerspectivePointSize=s.minPerspectivePointSize),void 0!==s.maxPerspectivePointSize&&(r.maxPerspectivePointSize=s.minPerspectivePointSize)):(r._preset="default",r.pointSize=s.pointSize,r.roundPoints=s.roundPoints,r.perspectivePoints=s.perspectivePoints,r.minPerspectivePointSize=s.minPerspectivePointSize,r.maxPerspectivePointSize=s.maxPerspectivePointSize),r.filterIntensity=s.filterIntensity,r.minIntensity=s.minIntensity,r.maxIntensity=s.maxIntensity,r}return C(i,[{key:"type",get:function(){return"PointsMaterial"}},{key:"presets",get:function(){return Xi}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||2,this.glRedraw()}},{key:"roundPoints",get:function(){return this._state.roundPoints},set:function(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"perspectivePoints",get:function(){return this._state.perspectivePoints},set:function(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minPerspectivePointSize",get:function(){return this._state.minPerspectivePointSize},set:function(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}},{key:"maxPerspectivePointSize",get:function(){return this._state.maxPerspectivePointSize},set:function(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}},{key:"filterIntensity",get:function(){return this._state.filterIntensity},set:function(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}},{key:"minIntensity",get:function(){return this._state.minIntensity},set:function(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}},{key:"maxIntensity",get:function(){return this._state.maxIntensity},set:function(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Xi[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Xi).join(", "))}}},{key:"hash",get:function(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Ji={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}},Zi=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"LinesMaterial",lineWidth:null}),s.preset?(r.preset=s.preset,void 0!==s.lineWidth&&(r.lineWidth=s.lineWidth)):(r._preset="default",r.lineWidth=s.lineWidth),r}return C(i,[{key:"type",get:function(){return"LinesMaterial"}},{key:"presets",get:function(){return Ji}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"preset",get:function(){return this._preset},set:function(e){if(e=e||"default",this._preset!==e){var t=Ji[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(Ji).join(", "))}}},{key:"hash",get:function(){return[""+this.lineWidth].join(";")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function qi(e,t){for(var i,r,s={},n=0,o=t.length;n1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),r=t.call(this,null,s);var n=s.canvasElement||document.getElementById(s.canvasId);if(!(n instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";r._tickifiedFunctions={};var o=!!s.transparent,a=!!s.alphaDepthMask;return r._aabbDirty=!0,r.viewer=e,r.occlusionTestCountdown=0,r.loading=0,r.startTime=(new Date).getTime(),r.models={},r.objects={},r._numObjects=0,r.visibleObjects={},r._numVisibleObjects=0,r.xrayedObjects={},r._numXRayedObjects=0,r.highlightedObjects={},r._numHighlightedObjects=0,r.selectedObjects={},r._numSelectedObjects=0,r.colorizedObjects={},r._numColorizedObjects=0,r.opacityObjects={},r._numOpacityObjects=0,r.offsetObjects={},r._numOffsetObjects=0,r._modelIds=null,r._objectIds=null,r._visibleObjectIds=null,r._xrayedObjectIds=null,r._highlightedObjectIds=null,r._selectedObjectIds=null,r._colorizedObjectIds=null,r._opacityObjectIds=null,r._offsetObjectIds=null,r._collidables={},r._compilables={},r._needRecompile=!1,r.types={},r.components={},r.sectionPlanes={},r.lights={},r.lightMaps={},r.reflectionMaps={},r.bitmaps={},r.lineSets={},r.realWorldOffset=s.realWorldOffset||new Float64Array([0,0,0]),r.canvas=new _t(b(r),{dontClear:!0,canvas:n,spinnerElementId:s.spinnerElementId,transparent:o,webgl2:!1!==s.webgl2,contextAttr:s.contextAttr||{},backgroundColor:s.backgroundColor,backgroundColorFromAmbientLight:s.backgroundColorFromAmbientLight,premultipliedAlpha:s.premultipliedAlpha}),r.canvas.on("boundary",(function(){r.glRedraw()})),r.canvas.on("webglContextFailed",(function(){alert("xeokit failed to find WebGL!")})),r._renderer=new Yt(b(r),{transparent:o,alphaDepthMask:a}),r._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;var e=null;this.getHash=function(){if(e)return e;var t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";for(var i=[],r=0,s=t;rthis._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},r._sectionPlanesState.setNumCachedSectionPlanes(s.numCachedSectionPlanes||0),r._lightsState=new function(){var e=$.vec4([0,0,0,0]),t=$.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];var i=null,r=null;this.getHash=function(){if(i)return i;for(var e,t=[],r=this.lights,s=0,n=r.length;s0&&t.push("/lm"),this.reflectionMaps.length>0&&t.push("/rm"),t.push(";"),i=t.join("")},this.addLight=function(e){this.lights.push(e),r=null,i=null},this.removeLight=function(e){for(var t=0,s=this.lights.length;t1&&void 0!==arguments[1])||arguments[1];e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}},{key:"_deRegisterVisibleObject",value:function(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}},{key:"_objectXRayedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}},{key:"_deRegisterXRayedObject",value:function(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}},{key:"_objectHighlightedUpdated",value:function(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}},{key:"_deRegisterHighlightedObject",value:function(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}},{key:"_objectSelectedUpdated",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}},{key:"_deRegisterSelectedObject",value:function(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}},{key:"_objectColorizeUpdated",value:function(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}},{key:"_deRegisterColorizedObject",value:function(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}},{key:"_objectOpacityUpdated",value:function(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}},{key:"_deRegisterOpacityObject",value:function(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}},{key:"_objectOffsetUpdated",value:function(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}},{key:"_deRegisterOffsetObject",value:function(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}},{key:"_webglContextLost",value:function(){for(var e in this.canvas.spinner.processes++,this.components)if(this.components.hasOwnProperty(e)){var t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}},{key:"_webglContextRestored",value:function(){var e=this.canvas.gl;for(var t in this.components)if(this.components.hasOwnProperty(t)){var i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}},{key:"capabilities",get:function(){return this._renderer.capabilities}},{key:"entityOffsetsEnabled",get:function(){return this._entityOffsetsEnabled}},{key:"pickSurfacePrecisionEnabled",get:function(){return!1}},{key:"logarithmicDepthBufferEnabled",get:function(){return this._logarithmicDepthBufferEnabled}},{key:"numCachedSectionPlanes",get:function(){return this._sectionPlanesState.getNumCachedSectionPlanes()},set:function(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}},{key:"pbrEnabled",get:function(){return this._pbrEnabled},set:function(e){this._pbrEnabled=!!e,this.glRedraw()}},{key:"dtxEnabled",get:function(){return this._dtxEnabled},set:function(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}},{key:"colorTextureEnabled",get:function(){return this._colorTextureEnabled},set:function(e){this._colorTextureEnabled=!!e,this.glRedraw()}},{key:"markerZOffset",get:function(){return null==this._markerZOffset?-.001:this._markerZOffset}},{key:"doOcclusionTest",value:function(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}},{key:"render",value:function(e){e&&_e.runTasks();var t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;var i,r,s=this._passes,n=this._clearEachPass;for(i=0;in&&(n=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),u=!0}u||(i=-100,r=-100,s=-100,n=100,o=100,a=100),this._aabb[0]=i,this._aabb[1]=r,this._aabb[2]=s,this._aabb[3]=n,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}},{key:"_setAABBDirty",value:function(){this._aabbDirty=!0,this.fire("boundary")}},{key:"pick",value:function(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;if(!e.snapToVertex&&!e.snapToEdge||e.canvasPos){(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");var i=e.includeEntities||e.include;i&&(e.includeEntityIds=qi(this,i));var r=e.excludeEntities||e.exclude;return r&&(e.excludeEntityIds=qi(this,r)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}this.error("Scene.snapPick() `canvasPos` parameter expected for `snapToVertex:true` or `snapToEdge:true`")}},{key:"snapPick",value:function(e){if(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos)return this._renderer.snapPick(e.canvasPos,e.snapRadius||30,e.snapToVertex,e.snapToEdge);this.error("Scene.snapPick() canvasPos parameter expected")}},{key:"clear",value:function(){var e;for(var t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}},{key:"clearLights",value:function(){for(var e=Object.keys(this.lights),t=0,i=e.length;to&&(o=t[3]),t[4]>a&&(a=t[4]),t[5]>l&&(l=t[5]),i=!0}})),i){var u=$.AABB3();return u[0]=r,u[1]=s,u[2]=n,u[3]=o,u[4]=a,u[5]=l,u}return this.aabb}},{key:"setObjectsVisible",value:function(e,t){return this.withObjects(e,(function(e){var i=e.visible!==t;return e.visible=t,i}))}},{key:"setObjectsCollidable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.collidable!==t;return e.collidable=t,i}))}},{key:"setObjectsCulled",value:function(e,t){return this.withObjects(e,(function(e){var i=e.culled!==t;return e.culled=t,i}))}},{key:"setObjectsSelected",value:function(e,t){return this.withObjects(e,(function(e){var i=e.selected!==t;return e.selected=t,i}))}},{key:"setObjectsHighlighted",value:function(e,t){return this.withObjects(e,(function(e){var i=e.highlighted!==t;return e.highlighted=t,i}))}},{key:"setObjectsXRayed",value:function(e,t){return this.withObjects(e,(function(e){var i=e.xrayed!==t;return e.xrayed=t,i}))}},{key:"setObjectsEdges",value:function(e,t){return this.withObjects(e,(function(e){var i=e.edges!==t;return e.edges=t,i}))}},{key:"setObjectsColorized",value:function(e,t){return this.withObjects(e,(function(e){e.colorize=t}))}},{key:"setObjectsOpacity",value:function(e,t){return this.withObjects(e,(function(e){var i=e.opacity!==t;return e.opacity=t,i}))}},{key:"setObjectsPickable",value:function(e,t){return this.withObjects(e,(function(e){var i=e.pickable!==t;return e.pickable=t,i}))}},{key:"setObjectsOffset",value:function(e,t){this.withObjects(e,(function(e){e.offset=t}))}},{key:"withObjects",value:function(e,t){le.isString(e)&&(e=[e]);for(var i=!1,r=0,s=e.length;rr&&(r=s,e.apply(void 0,A(i)))}));return this._tickifiedFunctions[t]={tickSubId:o,wrapperFunc:n},n}},{key:"destroy",value:function(){for(var e in f(w(i.prototype),"destroy",this).call(this),this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}]),i}(),er=1e3,tr=1001,ir=1002,rr=1003,sr=1004,nr=1004,or=1005,ar=1005,lr=1006,ur=1007,Ar=1007,cr=1008,hr=1008,dr=1009,pr=1010,fr=1011,vr=1012,gr=1013,mr=1014,_r=1015,yr=1016,br=1017,wr=1018,Br=1020,xr=1021,Pr=1022,Cr=1023,Mr=1024,Er=1025,Fr=1026,kr=1027,Ir=1028,Dr=1029,Sr=1030,Tr=1031,Lr=1033,Rr=33776,Ur=33777,Or=33778,Nr=33779,Qr=35840,Vr=35841,Hr=35842,jr=35843,Gr=36196,zr=37492,Wr=37496,Kr=37808,Xr=37809,Yr=37810,Jr=37811,Zr=37812,qr=37813,$r=37814,es=37815,ts=37816,is=37817,rs=37818,ss=37819,ns=37820,os=37821,as=36492,ls=3e3,us=3001,As=1e4,cs=10001,hs=10002,ds=10003,ps=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){var t=e.scene,i=e.scene._sectionPlanesState,r=e.scene._lightsState,s=e._geometry._state,n=e._state.billboard,o=e._state.stationary,a=i.getNumAllocatedSectionPlanes()>0,l=!!s.compressGeometry,u=[];u.push("#version 300 es"),u.push("// Lambertian drawing vertex shader"),u.push("in vec3 position;"),u.push("uniform mat4 modelMatrix;"),u.push("uniform mat4 viewMatrix;"),u.push("uniform mat4 projMatrix;"),u.push("uniform vec4 colorize;"),u.push("uniform vec3 offset;"),l&&u.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(u.push("uniform float logDepthBufFC;"),u.push("out float vFragDepth;"),u.push("bool isPerspectiveMatrix(mat4 m) {"),u.push(" return (m[2][3] == - 1.0);"),u.push("}"),u.push("out float isPerspective;"));a&&u.push("out vec4 vWorldPosition;");if(u.push("uniform vec4 lightAmbient;"),u.push("uniform vec4 materialColor;"),u.push("uniform vec3 materialEmissive;"),s.normalsBuf){u.push("in vec3 normal;"),u.push("uniform mat4 modelNormalMatrix;"),u.push("uniform mat4 viewNormalMatrix;");for(var A=0,c=r.lights.length;A= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),u.push(" }"),u.push(" return normalize(v);"),u.push("}"))}u.push("out vec4 vColor;"),"points"===s.primitiveName&&u.push("uniform float pointSize;");"spherical"!==n&&"cylindrical"!==n||(u.push("void billboard(inout mat4 mat) {"),u.push(" mat[0][0] = 1.0;"),u.push(" mat[0][1] = 0.0;"),u.push(" mat[0][2] = 0.0;"),"spherical"===n&&(u.push(" mat[1][0] = 0.0;"),u.push(" mat[1][1] = 1.0;"),u.push(" mat[1][2] = 0.0;")),u.push(" mat[2][0] = 0.0;"),u.push(" mat[2][1] = 0.0;"),u.push(" mat[2][2] =1.0;"),u.push("}"));u.push("void main(void) {"),u.push("vec4 localPosition = vec4(position, 1.0); "),u.push("vec4 worldPosition;"),l&&u.push("localPosition = positionsDecodeMatrix * localPosition;");s.normalsBuf&&(l?u.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):u.push("vec4 localNormal = vec4(normal, 0.0); "),u.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),u.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));u.push("mat4 viewMatrix2 = viewMatrix;"),u.push("mat4 modelMatrix2 = modelMatrix;"),o&&u.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===n||"cylindrical"===n?(u.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),u.push("billboard(modelMatrix2);"),u.push("billboard(viewMatrix2);"),u.push("billboard(modelViewMatrix);"),s.normalsBuf&&(u.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),u.push("billboard(modelNormalMatrix2);"),u.push("billboard(viewNormalMatrix2);"),u.push("billboard(modelViewNormalMatrix);")),u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(u.push("worldPosition = modelMatrix2 * localPosition;"),u.push("worldPosition.xyz = worldPosition.xyz + offset;"),u.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));s.normalsBuf&&u.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(u.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),u.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),u.push("float lambertian = 1.0;"),s.normalsBuf)for(var d=0,p=r.lights.length;d0,n=t.gammaOutput,o=[];o.push("#version 300 es"),o.push("// Lambertian drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;"));if(s){o.push("in vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(var a=0,l=i.getNumAllocatedSectionPlanes();a 0.0) { discard; }"),o.push("}")}"points"===r.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push(" discard;"),o.push("}"));t.logarithmicDepthBufferEnabled&&o.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");n?o.push("outColor = linearToGamma(vColor, gammaFactor);"):o.push("outColor = vColor;");return o.push("}"),o}(e)):(this.vertex=function(e){var t=e.scene;e._material;var i,r=e._state,s=t._sectionPlanesState,n=e._geometry._state,o=t._lightsState,a=r.billboard,l=r.background,u=r.stationary,A=function(e){if(!e._geometry._state.uvBuf)return!1;var t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),c=gs(e),h=s.getNumAllocatedSectionPlanes()>0,d=vs(e),p=!!n.compressGeometry,f=[];f.push("#version 300 es"),f.push("// Drawing vertex shader"),f.push("in vec3 position;"),p&&f.push("uniform mat4 positionsDecodeMatrix;");f.push("uniform mat4 modelMatrix;"),f.push("uniform mat4 viewMatrix;"),f.push("uniform mat4 projMatrix;"),f.push("out vec3 vViewPosition;"),f.push("uniform vec3 offset;"),h&&f.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("out float vFragDepth;"),f.push("bool isPerspectiveMatrix(mat4 m) {"),f.push(" return (m[2][3] == - 1.0);"),f.push("}"),f.push("out float isPerspective;"));o.lightMaps.length>0&&f.push("out vec3 vWorldNormal;");if(c){f.push("in vec3 normal;"),f.push("uniform mat4 modelNormalMatrix;"),f.push("uniform mat4 viewNormalMatrix;"),f.push("out vec3 vViewNormal;");for(var v=0,g=o.lights.length;v= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push(" }"),f.push(" return normalize(v);"),f.push("}"))}A&&(f.push("in vec2 uv;"),f.push("out vec2 vUV;"),p&&f.push("uniform mat3 uvDecodeMatrix;"));n.colors&&(f.push("in vec4 color;"),f.push("out vec4 vColor;"));"points"===n.primitiveName&&f.push("uniform float pointSize;");"spherical"!==a&&"cylindrical"!==a||(f.push("void billboard(inout mat4 mat) {"),f.push(" mat[0][0] = 1.0;"),f.push(" mat[0][1] = 0.0;"),f.push(" mat[0][2] = 0.0;"),"spherical"===a&&(f.push(" mat[1][0] = 0.0;"),f.push(" mat[1][1] = 1.0;"),f.push(" mat[1][2] = 0.0;")),f.push(" mat[2][0] = 0.0;"),f.push(" mat[2][1] = 0.0;"),f.push(" mat[2][2] =1.0;"),f.push("}"));if(d){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(var m=0,_=o.lights.length;m<_;m++)o.lights[m].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+m+";"),f.push("uniform mat4 shadowProjMatrix"+m+";"),f.push("out vec4 vShadowPosFromLight"+m+";"))}f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),p&&f.push("localPosition = positionsDecodeMatrix * localPosition;");c&&(p?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));f.push("mat4 viewMatrix2 = viewMatrix;"),f.push("mat4 modelMatrix2 = modelMatrix;"),u?f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"):l&&f.push("viewMatrix2[3] = vec4(0.0, 0.0, 0.0 ,1.0);");"spherical"===a||"cylindrical"===a?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),c&&(f.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));if(c){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),o.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(var y=0,b=o.lights.length;y0,l=gs(e),u=r.uvBuf,A="PhongMaterial"===o.type,c="MetallicMaterial"===o.type,h="SpecularMaterial"===o.type,d=vs(e);t.gammaInput;var p=t.gammaOutput,f=[];f.push("#version 300 es"),f.push("// Drawing fragment shader"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("in float isPerspective;"),f.push("uniform float logDepthBufFC;"),f.push("in float vFragDepth;"));d&&(f.push("float unpackDepth (vec4 color) {"),f.push(" const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push(" return dot(color, bitShift);"),f.push("}"));f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push(" return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),p&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}"));if(a){f.push("in vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var v=0;v0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),n.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push(" vec3 color;"),f.push(" vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push(" vec3 diffuse;"),f.push(" vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push(" vec3 position;"),f.push(" vec3 viewNormal;"),f.push(" vec3 worldNormal;"),f.push(" vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push(" vec3 diffuseColor;"),f.push(" float specularRoughness;"),f.push(" vec3 specularColor;"),f.push(" float shine;"),f.push("};"),A&&((n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = "+fs[n.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" vec3 radiance = texture(reflectionMap, reflectVec).rgb * 0.2;"),f.push(" radiance *= PI;"),f.push(" reflectedLight.specular += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push(" vec3 irradiance = dotNL * directLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(c||h)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push(" float r = ggxRoughness + 0.0001;"),f.push(" return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),f.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),n.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push(" vec3 envMapColor = "+fs[n.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push(" return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push(" return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push(" float a2 = ( alpha * alpha );"),f.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float alpha = ( roughness * roughness );"),f.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push(" vec3 F = F_Schlick( specularColor, dotLH );"),f.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push(" float D = D_GGX( alpha, dotNH );"),f.push(" return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),f.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),f.push(" vec4 r = roughness * c0 + c1;"),f.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push(" return specularColor * AB.x + AB.y;"),f.push("}"),(n.lightMaps.length>0||n.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),n.lightMaps.length>0&&(f.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),f.push(" irradiance *= PI;"),f.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),n.reflectionMaps.length>0&&(f.push(" vec3 reflectVec = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),f.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}")));f.push("in vec3 vViewPosition;"),r.colors&&f.push("in vec4 vColor;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("in vec2 vUV;");l&&(n.lightMaps.length>0&&f.push("in vec3 vWorldNormal;"),f.push("in vec3 vViewNormal;"));o.ambient&&f.push("uniform vec3 materialAmbient;");o.baseColor&&f.push("uniform vec3 materialBaseColor;");void 0!==o.alpha&&null!==o.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;");o.emissive&&f.push("uniform vec3 materialEmissive;");o.diffuse&&f.push("uniform vec3 materialDiffuse;");void 0!==o.glossiness&&null!==o.glossiness&&f.push("uniform float materialGlossiness;");void 0!==o.shininess&&null!==o.shininess&&f.push("uniform float materialShininess;");o.specular&&f.push("uniform vec3 materialSpecular;");void 0!==o.metallic&&null!==o.metallic&&f.push("uniform float materialMetallic;");void 0!==o.roughness&&null!==o.roughness&&f.push("uniform float materialRoughness;");void 0!==o.specularF0&&null!==o.specularF0&&f.push("uniform float materialSpecularF0;");u&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;"));u&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;"));u&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;"));u&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;"));l&&u&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;"));l&&u&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;"));l&&u&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;"));l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push(" vec2 st0 = dFdx( uv.st );"),f.push(" vec2 st1 = dFdy( uv.st );"),f.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push(" vec3 N = normalize( surf_norm );"),f.push(" vec3 mapN = texture( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push(" mat3 tsn = mat3( S, T, N );"),f.push(" return normalize( tsn * mapN );"),f.push("}"));u&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;"));u&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;"));l&&u&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;"));l&&u&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;"));l&&u&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;"));l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push(" float fr = abs(dot(eyeDir, normal));"),f.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push(" return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float diffuseFresnelCenterBias;"),f.push("uniform float diffuseFresnelEdgeBias;"),f.push("uniform float diffuseFresnelPower;"),f.push("uniform vec3 diffuseFresnelCenterColor;"),f.push("uniform vec3 diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float specularFresnelCenterBias;"),f.push("uniform float specularFresnelEdgeBias;"),f.push("uniform float specularFresnelPower;"),f.push("uniform vec3 specularFresnelCenterColor;"),f.push("uniform vec3 specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float alphaFresnelCenterBias;"),f.push("uniform float alphaFresnelEdgeBias;"),f.push("uniform float alphaFresnelPower;"),f.push("uniform vec3 alphaFresnelCenterColor;"),f.push("uniform vec3 alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float materialSpecularF0FresnelCenterBias;"),f.push("uniform float materialSpecularF0FresnelEdgeBias;"),f.push("uniform float materialSpecularF0FresnelPower;"),f.push("uniform vec3 materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3 materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float emissiveFresnelCenterBias;"),f.push("uniform float emissiveFresnelEdgeBias;"),f.push("uniform float emissiveFresnelPower;"),f.push("uniform vec3 emissiveFresnelCenterColor;"),f.push("uniform vec3 emissiveFresnelEdgeColor;")));if(f.push("uniform vec4 lightAmbient;"),l)for(var g=0,m=n.lights.length;g 0.0) { discard; }"),f.push("}")}"points"===r.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push(" discard;"),f.push("}"));f.push("float occlusion = 1.0;"),o.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);");o.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):o.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);");r.colors&&f.push("diffuseColor *= vColor.rgb;");o.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3 emissiveColor = vec3(0.0, 0.0, 0.0);");o.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);");void 0!==o.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;");r.colors&&f.push("alpha *= vColor.a;");void 0!==o.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;");void 0!==o.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;");void 0!==o.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;");void 0!==o.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;");u&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;"));u&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+fs[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;"));u&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+fs[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;"));u&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+fs[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;"));u&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+fs[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;"));u&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture(alphaMap, textureCoord).r;"));u&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture(occlusionMap, textureCoord).r;"));if(l&&(n.lights.length>0||n.lightMaps.length>0||n.reflectionMaps.length>0)){u&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),u&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture(specularMap, textureCoord).rgb;")),u&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture(glossinessMap, textureCoord).r;")),u&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),u&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture(metallicMap, textureCoord).r;")),u&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture(roughnessMap, textureCoord).r;")),u&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push(" discard;"),f.push("}"),f.push("IncidentLight light;"),f.push("Material material;"),f.push("Geometry geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3 viewLightDir;"),A&&(f.push("material.diffuseColor = diffuseColor;"),f.push("material.specularColor = specular;"),f.push("material.shine = materialShininess;")),h&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor = specular;")),c&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position = vViewPosition;"),n.lightMaps.length>0&&f.push("geometry.worldNormal = normalize(vWorldNormal);"),f.push("geometry.viewNormal = viewNormal;"),f.push("geometry.viewEyeDir = viewEyeDir;"),A&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(h||c)&&(n.lightMaps.length>0||n.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(var w=0,B=n.lights.length;w0)for(var f=r._sectionPlanesState.sectionPlanes,v=t.renderFlags,g=0;g0&&(this._uLightMap="lightMap"),s.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[];for(A=0,c=n.sectionPlanes.length;A0&&n.lightMaps[0].texture&&this._uLightMap&&(a.bindTexture(this._uLightMap,n.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),n.reflectionMaps.length>0&&n.reflectionMaps[0].texture&&this._uReflectionMap&&(a.bindTexture(this._uReflectionMap,n.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,r.gammaFactor),this._baseTextureUnit=e.textureUnit};var ws=C((function e(t){x(this,e),this.vertex=function(e){var t=e.scene,i=t._lightsState,r=function(e){var t=e._geometry._state.primitiveName;if((e._geometry._state.autoVertexNormals||e._geometry._state.normalsBuf)&&("triangles"===t||"triangle-strip"===t||"triangle-fan"===t))return!0;return!1}(e),s=t._sectionPlanesState.getNumAllocatedSectionPlanes()>0,n=!!e._geometry._state.compressGeometry,o=e._state.billboard,a=e._state.stationary,l=[];l.push("#version 300 es"),l.push("// EmphasisFillShaderSource vertex shader"),l.push("in vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),n&&l.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),l.push("out float vFragDepth;"),l.push("bool isPerspectiveMatrix(mat4 m) {"),l.push(" return (m[2][3] == - 1.0);"),l.push("}"),l.push("out float isPerspective;"));s&&l.push("out vec4 vWorldPosition;");if(l.push("uniform vec4 lightAmbient;"),l.push("uniform vec4 fillColor;"),r){l.push("in vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(var u=0,A=i.lights.length;u= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push(" }"),l.push(" return normalize(v);"),l.push("}"))}l.push("out vec4 vColor;"),("spherical"===o||"cylindrical"===o)&&(l.push("void billboard(inout mat4 mat) {"),l.push(" mat[0][0] = 1.0;"),l.push(" mat[0][1] = 0.0;"),l.push(" mat[0][2] = 0.0;"),"spherical"===o&&(l.push(" mat[1][0] = 0.0;"),l.push(" mat[1][1] = 1.0;"),l.push(" mat[1][2] = 0.0;")),l.push(" mat[2][0] = 0.0;"),l.push(" mat[2][1] = 0.0;"),l.push(" mat[2][2] =1.0;"),l.push("}"));l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),n&&l.push("localPosition = positionsDecodeMatrix * localPosition;");r&&(n?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;"));l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),a&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===o||"cylindrical"===o?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),r&&(l.push("mat4 modelViewNormalMatrix = viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));r&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);");if(l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),r)for(var h=0,d=i.lights.length;h0,n=[];n.push("#version 300 es"),n.push("// Lambertian drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));r&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(s){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}"points"===e._geometry._state.primitiveName&&(n.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),n.push("float r = dot(cxy, cxy);"),n.push("if (r > 1.0) {"),n.push(" discard;"),n.push("}"));t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");r?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var Bs=new Q({}),xs=$.vec3(),Ps=function(e,t){this.id=Bs.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new ws(t),this._allocate(t)},Cs={};Ps.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Cs[t];return i||(i=new Ps(t,e),Cs[t]=i,re.memory.programs++),i._useCount++,i},Ps.prototype.put=function(){0==--this._useCount&&(Bs.removeItem(this.id),this._program&&this._program.destroy(),delete Cs[this._hash],re.memory.programs--)},Ps.prototype.webglContextRestored=function(){this._program=null},Ps.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var r=this._scene,s=r.camera,n=r.canvas.gl,o=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,a=t._state,l=t._geometry._state,u=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),n.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(a.originHash,u):s.viewMatrix),n.uniformMatrix4fv(this._uViewNormalMatrix,!1,s.viewNormalMatrix),a.clippable){var A=r._sectionPlanesState.getNumAllocatedSectionPlanes(),c=r._sectionPlanesState.sectionPlanes.length;if(A>0)for(var h=r._sectionPlanesState.sectionPlanes,d=t.renderFlags,p=0;p0,r=!!e._geometry._state.compressGeometry,s=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Edges drawing vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec4 edgeColor;"),o.push("uniform vec3 offset;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));i&&o.push("out vec4 vWorldPosition;");o.push("out vec4 vColor;"),("spherical"===s||"cylindrical"===s)&&(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"===s&&(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;"),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===s||"cylindrical"===s?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));o.push("vColor = edgeColor;"),i&&o.push("vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=e.scene._sectionPlanesState,r=e.scene.gammaOutput,s=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Edges drawing fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),t.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;"));r&&(n.push("uniform float gammaFactor;"),n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}"));if(s){n.push("in vec4 vWorldPosition;"),n.push("uniform bool clippable;");for(var o=0,a=i.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),n.push("}")}t.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");r?n.push("outColor = linearToGamma(vColor, gammaFactor);"):n.push("outColor = vColor;");return n.push("}"),n}(t)}));var Es=new Q({}),Fs=$.vec3(),ks=function(e,t){this.id=Es.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ms(t),this._allocate(t)},Is={};ks.get=function(e){var t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Is[t];return i||(i=new ks(t,e),Is[t]=i,re.memory.programs++),i._useCount++,i},ks.prototype.put=function(){0==--this._useCount&&(Es.removeItem(this.id),this._program&&this._program.destroy(),delete Is[this._hash],re.memory.programs--)},ks.prototype.webglContextRestored=function(){this._program=null},ks.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);var r,s,n=this._scene,o=n.camera,a=n.canvas.gl,l=t._state,u=t._geometry,A=u._state,c=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(l.originHash,c):o.viewMatrix),l.clippable){var h=n._sectionPlanesState.getNumAllocatedSectionPlanes(),d=n._sectionPlanesState.sectionPlanes.length;if(h>0)for(var p=n._sectionPlanesState.sectionPlanes,f=t.renderFlags,v=0;v0,r=!!e._geometry._state.compressGeometry,s=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh picking vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("out vec4 vViewPosition;"),o.push("uniform vec3 offset;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==s&&"cylindrical"!==s||(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"===s&&(o.push(" mat[1][0] = 0.0;"),o.push(" mat[1][1] = 1.0;"),o.push(" mat[1][2] = 0.0;")),o.push(" mat[2][0] = 0.0;"),o.push(" mat[2][1] = 0.0;"),o.push(" mat[2][2] =1.0;"),o.push("}"));o.push("uniform vec2 pickClipPos;"),o.push("vec4 remapClipPos(vec4 clipPos) {"),o.push(" clipPos.xy /= clipPos.w;"),o.push(" clipPos.xy -= pickClipPos;"),o.push(" clipPos.xy *= clipPos.w;"),o.push(" return clipPos;"),o.push("}"),o.push("void main(void) {"),o.push("vec4 localPosition = vec4(position, 1.0); "),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"!==s&&"cylindrical"!==s||(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"));o.push(" vec4 worldPosition = modelMatrix2 * localPosition;"),o.push(" worldPosition.xyz = worldPosition.xyz + offset;"),o.push(" vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = remapClipPos(clipPos);"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Mesh picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"));if(s.push("uniform vec4 pickColor;"),r){s.push("uniform bool clippable;"),s.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),s.push("}")}t.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return s.push(" outColor = pickColor; "),s.push("}"),s}(t)}));var Ss=$.vec3(),Ts=function(e,t){this._hash=e,this._shaderSource=new Ds(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ls={};Ts.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),i=Ls[t];if(!i){if((i=new Ts(t,e)).errors)return console.log(i.errors.join("\n")),null;Ls[t]=i,re.memory.programs++}return i._useCount++,i},Ts.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ls[this._hash],re.memory.programs--)},Ts.prototype.webglContextRestored=function(){this._program=null},Ts.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,s=t._state,n=t._material._state,o=t._geometry._state,a=t.origin;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCPickViewMatrix(s.originHash,a):e.pickViewMatrix),s.clippable){var l=i._sectionPlanesState.getNumAllocatedSectionPlanes(),u=i._sectionPlanesState.sectionPlanes.length;if(l>0)for(var A=i._sectionPlanesState.sectionPlanes,c=t.renderFlags,h=0;h>24&255,b=_>>16&255,w=_>>8&255,B=255&_;r.uniform4f(this._uPickColor,B/255,w/255,b/255,y/255),r.uniform2fv(this._uPickClipPos,e.pickClipPos),o.indicesBuf?(r.drawElements(o.primitive,o.indicesBuf.numItems,o.indicesBuf.itemType,0),e.drawElements++):o.positions&&r.drawArrays(r.TRIANGLES,0,o.positions.numItems)},Ts.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new It(i,this._shaderSource),this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(var s=0,n=t._sectionPlanesState.sectionPlanes.length;s0,r=!!e._geometry._state.compressGeometry,s=[];s.push("#version 300 es"),s.push("// Surface picking vertex shader"),s.push("in vec3 position;"),s.push("in vec4 color;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform vec3 offset;"),i&&(s.push("uniform bool clippable;"),s.push("out vec4 vWorldPosition;"));t.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("uniform vec2 pickClipPos;"),s.push("vec4 remapClipPos(vec4 clipPos) {"),s.push(" clipPos.xy /= clipPos.w;"),s.push(" clipPos.xy -= pickClipPos;"),s.push(" clipPos.xy *= clipPos.w;"),s.push(" return clipPos;"),s.push("}"),s.push("out vec4 vColor;"),r&&s.push("uniform mat4 positionsDecodeMatrix;");s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),r&&s.push("localPosition = positionsDecodeMatrix * localPosition;");s.push(" vec4 worldPosition = modelMatrix * localPosition; "),s.push(" worldPosition.xyz = worldPosition.xyz + offset;"),s.push(" vec4 viewPosition = viewMatrix * worldPosition;"),i&&s.push(" vWorldPosition = worldPosition;");s.push(" vColor = color;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(s.push("vFragDepth = 1.0 + clipPos.w;"),s.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return s.push("gl_Position = remapClipPos(clipPos);"),s.push("}"),s}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Surface picking fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),s.push("in vec4 vColor;"),t.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"));if(r){s.push("uniform bool clippable;"),s.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),s.push("}")}t.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return s.push(" outColor = vColor;"),s.push("}"),s}(t)}));var Us=$.vec3(),Os=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Rs(t),this._allocate(t)},Ns={};Os.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";"),i=Ns[t];if(!i){if((i=new Os(t,e)).errors)return console.log(i.errors.join("\n")),null;Ns[t]=i,re.memory.programs++}return i._useCount++,i},Os.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ns[this._hash],re.memory.programs--)},Os.prototype.webglContextRestored=function(){this._program=null},Os.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,s=t._state,n=t._material._state,o=t._geometry,a=t._geometry._state,l=t.origin,u=n.backfaces,A=n.frontface,c=i.camera.project,h=o._getPickTrianglePositions(),d=o._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){var p=2/(Math.log(c.far+1)/Math.LN2);r.uniform1f(this._uLogDepthBufFC,p)}if(r.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(s.originHash,l):e.pickViewMatrix),s.clippable){var f=i._sectionPlanesState.getNumAllocatedSectionPlanes(),v=i._sectionPlanesState.sectionPlanes.length;if(f>0)for(var g=i._sectionPlanesState.sectionPlanes,m=t.renderFlags,_=0;_0,r=!!e._geometry._state.compressGeometry,s=e._state.billboard,n=e._state.stationary,o=[];o.push("#version 300 es"),o.push("// Mesh occlusion vertex shader"),o.push("in vec3 position;"),o.push("uniform mat4 modelMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform vec3 offset;"),r&&o.push("uniform mat4 positionsDecodeMatrix;");i&&o.push("out vec4 vWorldPosition;");t.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),o.push("out float vFragDepth;"),o.push("bool isPerspectiveMatrix(mat4 m) {"),o.push(" return (m[2][3] == - 1.0);"),o.push("}"),o.push("out float isPerspective;"));"spherical"!==s&&"cylindrical"!==s||(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"===s&&(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;"),r&&o.push("localPosition = positionsDecodeMatrix * localPosition;");o.push("mat4 viewMatrix2 = viewMatrix;"),o.push("mat4 modelMatrix2 = modelMatrix;"),n&&o.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;");"spherical"===s||"cylindrical"===s?(o.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),o.push("billboard(modelMatrix2);"),o.push("billboard(viewMatrix2);"),o.push("billboard(modelViewMatrix);"),o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(o.push("worldPosition = modelMatrix2 * localPosition;"),o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition = viewMatrix2 * worldPosition; "));i&&o.push(" vWorldPosition = worldPosition;");o.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(o.push("vFragDepth = 1.0 + clipPos.w;"),o.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"));return o.push("gl_Position = clipPos;"),o.push("}"),o}(t),this.fragment=function(e){var t=e.scene,i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,s=[];s.push("#version 300 es"),s.push("// Mesh occlusion fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),t.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;"));if(r){s.push("uniform bool clippable;"),s.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),s.push("}")}s.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&s.push("gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;");return s.push("}"),s}(t)}));var Vs=$.vec3(),Hs=function(e,t){this._hash=e,this._shaderSource=new Qs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},js={};Hs.get=function(e){var t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.occlusionHash].join(";"),i=js[t];if(!i){if((i=new Hs(t,e)).errors)return console.log(i.errors.join("\n")),null;js[t]=i,re.memory.programs++}return i._useCount++,i},Hs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete js[this._hash],re.memory.programs--)},Hs.prototype.webglContextRestored=function(){this._program=null},Hs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene,r=i.canvas.gl,s=t._material._state,n=t._state,o=t._geometry._state,a=t.origin;if(!(s.alpha<1)){if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){var l=s.backfaces;e.backfaces!==l&&(l?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),e.backfaces=l);var u=s.frontface;e.frontface!==u&&(u?r.frontFace(r.CCW):r.frontFace(r.CW),e.frontface=u),this._lastMaterialId=s.id}var A=i.camera;if(r.uniformMatrix4fv(this._uViewMatrix,!1,a?e.getRTCViewMatrix(n.originHash,a):A.viewMatrix),n.clippable){var c=i._sectionPlanesState.getNumAllocatedSectionPlanes(),h=i._sectionPlanesState.sectionPlanes.length;if(c>0)for(var d=i._sectionPlanesState.sectionPlanes,p=t.renderFlags,f=0;f0,i=!!e._geometry._state.compressGeometry,r=[];r.push("// Mesh shadow vertex shader"),r.push("in vec3 position;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 shadowViewMatrix;"),r.push("uniform mat4 shadowProjMatrix;"),r.push("uniform vec3 offset;"),i&&r.push("uniform mat4 positionsDecodeMatrix;");t&&r.push("out vec4 vWorldPosition;");r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),r.push("vec4 worldPosition;"),i&&r.push("localPosition = positionsDecodeMatrix * localPosition;");r.push("worldPosition = modelMatrix * localPosition;"),r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&r.push("vWorldPosition = worldPosition;");return r.push(" gl_Position = shadowProjMatrix * viewPosition;"),r.push("}"),r}(t),this.fragment=function(e){var t=e.scene;t.canvas.gl;var i=t._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("// Mesh 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"),r){s.push("uniform bool clippable;"),s.push("in vec4 vWorldPosition;");for(var n=0;n 0.0) { discard; }"),s.push("}")}return s.push("outColor = encodeFloat(gl_FragCoord.z);"),s.push("}"),s}(t)}));var zs=function(e,t){this._hash=e,this._shaderSource=new Gs(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Ws={};zs.get=function(e){var t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";"),r=Ws[i];if(!r){if((r=new zs(i,e)).errors)return console.log(r.errors.join("\n")),null;Ws[i]=r,re.memory.programs++}return r._useCount++,r},zs.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Ws[this._hash],re.memory.programs--)},zs.prototype.webglContextRestored=function(){this._program=null},zs.prototype.drawMesh=function(e,t){this._program||this._allocate(t);var i=this._scene.canvas.gl,r=t._material._state,s=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){var n=r.backfaces;e.backfaces!==n&&(n?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=n);var o=r.frontface;e.frontface!==o&&(o?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=o),e.lineWidth!==r.lineWidth&&(i.lineWidth(r.lineWidth),e.lineWidth=r.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,r.pointSize),this._lastMaterialId=r.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),s.combineGeometry){var a=t.vertexBufs;a.id!==this._lastVertexBufsId&&(a.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=a.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),s.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,s.positionsDecodeMatrix),s.combineGeometry?s.indicesBufCombined&&(s.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),s.indicesBuf&&(s.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=s.id),s.combineGeometry?s.indicesBufCombined&&(i.drawElements(s.primitive,s.indicesBufCombined.numItems,s.indicesBufCombined.itemType,0),e.drawElements++):s.indicesBuf?(i.drawElements(s.primitive,s.indicesBuf.numItems,s.indicesBuf.itemType,0),e.drawElements++):s.positions&&(i.drawArrays(i.TRIANGLES,0,s.positions.numItems),e.drawArrays++)},zs.prototype._allocate=function(e){var t=e.scene,i=t.canvas.gl;if(this._program=new It(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)this.errors=this._program.errors;else{var r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uShadowViewMatrix=r.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=r.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(var s=0,n=t._sectionPlanesState.sectionPlanes.length;s0)for(var s,n,o,a=0,l=this._uSectionPlanes.length;a1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s)).renderOrder=s.renderOrder||0,r.originalSystemId=s.originalSystemId||r.id,r.renderFlags=new Ks,r._state=new qt({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==s.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!s.stationary,background:!!s.background,billboard:r._checkBillboard(s.billboard),layer:null,colorize:null,pickID:r.scene._renderer.getPickID(b(r)),drawHash:"",pickHash:"",offset:$.vec3(),origin:null,originHash:null}),r._drawRenderer=null,r._shadowRenderer=null,r._emphasisFillRenderer=null,r._emphasisEdgesRenderer=null,r._pickMeshRenderer=null,r._pickTriangleRenderer=null,r._occlusionRenderer=null,r._geometry=s.geometry?r._checkComponent2(["ReadableGeometry","VBOGeometry"],s.geometry):r.scene.geometry,r._material=s.material?r._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],s.material):r.scene.material,r._xrayMaterial=s.xrayMaterial?r._checkComponent("EmphasisMaterial",s.xrayMaterial):r.scene.xrayMaterial,r._highlightMaterial=s.highlightMaterial?r._checkComponent("EmphasisMaterial",s.highlightMaterial):r.scene.highlightMaterial,r._selectedMaterial=s.selectedMaterial?r._checkComponent("EmphasisMaterial",s.selectedMaterial):r.scene.selectedMaterial,r._edgeMaterial=s.edgeMaterial?r._checkComponent("EdgeMaterial",s.edgeMaterial):r.scene.edgeMaterial,r._parentNode=null,r._aabb=null,r._aabbDirty=!0,r._numTriangles=r._geometry?r._geometry.numTriangles:0,r.scene._aabbDirty=!0,r._scale=$.vec3(),r._quaternion=$.identityQuaternion(),r._rotation=$.vec3(),r._position=$.vec3(),r._worldMatrix=$.identityMat4(),r._worldNormalMatrix=$.identityMat4(),r._localMatrixDirty=!0,r._worldMatrixDirty=!0,r._worldNormalMatrixDirty=!0;var n=s.origin||s.rtcCenter;if(n&&(r._state.origin=$.vec3(n),r._state.originHash=n.join()),s.matrix?r.matrix=s.matrix:(r.scale=s.scale,r.position=s.position,s.quaternion||(r.rotation=s.rotation)),r._isObject=s.isObject,r._isObject&&r.scene._registerObject(b(r)),r._isModel=s.isModel,r._isModel&&r.scene._registerModel(b(r)),r.visible=s.visible,r.culled=s.culled,r.pickable=s.pickable,r.clippable=s.clippable,r.collidable=s.collidable,r.castsShadow=s.castsShadow,r.receivesShadow=s.receivesShadow,r.xrayed=s.xrayed,r.highlighted=s.highlighted,r.selected=s.selected,r.edges=s.edges,r.layer=s.layer,r.colorize=s.colorize,r.opacity=s.opacity,r.offset=s.offset,s.parentId){var o=r.scene.components[s.parentId];o?o.isNode?o.addChild(b(r)):r.error("Parent is not a Node: '"+s.parentId+"'"):r.error("Parent not found: '"+s.parentId+"'"),r._parentNode=o}else s.parent&&(s.parent.isNode||r.error("Parent is not a Node"),s.parent.addChild(b(r)),r._parentNode=s.parent);return r.compile(),r}return C(i,[{key:"type",get:function(){return"Mesh"}},{key:"isMesh",get:function(){return!0}},{key:"parent",get:function(){return this._parentNode}},{key:"geometry",get:function(){return this._geometry}},{key:"material",get:function(){return this._material}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"matrix",get:function(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=$.identityMat4()),$.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix},set:function(e){this.__localMatrix||(this.__localMatrix=$.identityMat4()),this.__localMatrix.set(e||sn),$.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}},{key:"worldMatrix",get:function(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}},{key:"worldNormalMatrix",get:function(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}},{key:"isEntity",get:function(){return!0}},{key:"isModel",get:function(){return this._isModel}},{key:"isObject",get:function(){return this._isObject}},{key:"aabb",get:function(){return this._aabbDirty&&this._updateAABB(),this._aabb}},{key:"origin",get:function(){return this._state.origin},set:function(e){e?(this._state.origin||(this._state.origin=$.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"rtcCenter",get:function(){return this.origin},set:function(e){this.origin=e}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"visible",get:function(){return this._state.visible},set:function(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}},{key:"xrayed",get:function(){return this._state.xrayed},set:function(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}},{key:"highlighted",get:function(){return this._state.highlighted},set:function(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}},{key:"selected",get:function(){return this._state.selected},set:function(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}},{key:"edges",get:function(){return this._state.edges},set:function(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}},{key:"culled",get:function(){return this._state.culled},set:function(e){this._state.culled=!!e,this.glRedraw()}},{key:"clippable",get:function(){return this._state.clippable},set:function(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}},{key:"collidable",get:function(){return this._state.collidable},set:function(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}},{key:"pickable",get:function(){return this._state.pickable},set:function(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}},{key:"receivesShadow",get:function(){return this._state.receivesShadow},set:function(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}},{key:"saoEnabled",get:function(){return!1}},{key:"colorize",get:function(){return this._state.colorize},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);var i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}},{key:"opacity",get:function(){return this._state.colorize[3]},set:function(e){var t=this._state.colorize;t||((t=this._state.colorize=new Float32Array(4))[0]=1,t[1]=1,t[2]=1);var i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}},{key:"transparent",get:function(){return 2===this._material.alphaMode||this._state.colorize[3]<1}},{key:"layer",get:function(){return this._state.layer},set:function(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}},{key:"stationary",get:function(){return this._state.stationary}},{key:"billboard",get:function(){return this._state.billboard}},{key:"offset",get:function(){return this._state.offset},set:function(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}},{key:"isDrawable",get:function(){return!0}},{key:"isStateSortable",get:function(){return!0}},{key:"xrayMaterial",get:function(){return this._xrayMaterial}},{key:"highlightMaterial",get:function(){return this._highlightMaterial}},{key:"selectedMaterial",get:function(){return this._selectedMaterial}},{key:"edgeMaterial",get:function(){return this._edgeMaterial}},{key:"_checkBillboard",value:function(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}},{key:"compile",value:function(){var e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=ys.get(this),this._emphasisFillRenderer=Ps.get(this),this._emphasisEdgesRenderer=ks.get(this));var t=this._makePickHash();if(this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Ts.get(this)),this._state.occluder){var i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=Hs.get(this))}}},{key:"_setLocalMatrixDirty",value:function(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}},{key:"_setWorldMatrixDirty",value:function(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}},{key:"_buildWorldMatrix",value:function(){var e=this.matrix;if(this._parentNode)$.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(var t=0,i=e.length;t0)for(var i=0;i-1){var L=k.geometry._state,R=k.scene,U=R.camera,O=R.canvas;if("triangles"===L.primitiveName){S.primitive="triangle";var N,Q,V,H=T,j=L.indices,G=L.positions;if(j){var z=j[H+0],W=j[H+1],K=j[H+2];n[0]=z,n[1]=W,n[2]=K,S.indices=n,N=3*z,Q=3*W,V=3*K}else V=(Q=(N=3*H)+3)+3;if(i[0]=G[N+0],i[1]=G[N+1],i[2]=G[N+2],r[0]=G[Q+0],r[1]=G[Q+1],r[2]=G[Q+2],s[0]=G[V+0],s[1]=G[V+1],s[2]=G[V+2],L.compressGeometry){var X=L.positionsDecodeMatrix;X&&(Ii.decompressPosition(i,X,i),Ii.decompressPosition(r,X,r),Ii.decompressPosition(s,X,s))}S.canvasPos?$.canvasPosToLocalRay(O.canvas,k.origin?Le(I,k.origin):I,D,k.worldMatrix,S.canvasPos,e,t):S.origin&&S.direction&&$.worldRayToLocalRay(k.worldMatrix,S.origin,S.direction,e,t),$.normalizeVec3(t),$.rayPlaneIntersect(e,t,i,r,s,o),S.localPos=o,S.position=o,v[0]=o[0],v[1]=o[1],v[2]=o[2],v[3]=1,$.transformVec4(k.worldMatrix,v,g),a[0]=g[0],a[1]=g[1],a[2]=g[2],S.canvasPos&&k.origin&&(a[0]+=k.origin[0],a[1]+=k.origin[1],a[2]+=k.origin[2]),S.worldPos=a,$.transformVec4(U.matrix,g,m),l[0]=m[0],l[1]=m[1],l[2]=m[2],S.viewPos=l,$.cartesianToBarycentric(o,i,r,s,u),S.bary=u;var Y=L.normals;if(Y){if(L.compressGeometry){var J=3*z,Z=3*W,q=3*K;Ii.decompressNormal(Y.subarray(J,J+2),A),Ii.decompressNormal(Y.subarray(Z,Z+2),c),Ii.decompressNormal(Y.subarray(q,q+2),h)}else A[0]=Y[N],A[1]=Y[N+1],A[2]=Y[N+2],c[0]=Y[Q],c[1]=Y[Q+1],c[2]=Y[Q+2],h[0]=Y[V],h[1]=Y[V+1],h[2]=Y[V+2];var ee=$.addVec3($.addVec3($.mulVec3Scalar(A,u[0],_),$.mulVec3Scalar(c,u[1],y),b),$.mulVec3Scalar(h,u[2],w),B);S.worldNormal=$.normalizeVec3($.transformVec3(k.worldNormalMatrix,ee,x))}var te=L.uv;if(te){if(d[0]=te[2*z],d[1]=te[2*z+1],p[0]=te[2*W],p[1]=te[2*W+1],f[0]=te[2*K],f[1]=te[2*K+1],L.compressGeometry){var ie=L.uvDecodeMatrix;ie&&(Ii.decompressUV(d,ie,d),Ii.decompressUV(p,ie,p),Ii.decompressUV(f,ie,f))}S.uv=$.addVec3($.addVec3($.mulVec2Scalar(d,u[0],P),$.mulVec2Scalar(p,u[1],C),M),$.mulVec2Scalar(f,u[2],E),F)}}}}}();function an(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);var i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);var r=e.height||1;r<0&&(console.error("negative height not allowed - will invert"),r*=-1);var s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<3&&(s=3);var n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);var o,a,l,u,A,c,h,d,p,f,v,g=!!e.openEnded,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=r/2,B=r/n,x=2*Math.PI/s,P=1/s,C=(t-i)/n,M=[],E=[],F=[],k=[],I=(90-180*Math.atan(r/(i-t))/Math.PI)/90;for(o=0;o<=n;o++)for(A=t-o*C,c=w-o*B,a=0;a<=s;a++)l=Math.sin(a*x),u=Math.cos(a*x),E.push(A*l),E.push(I),E.push(A*u),F.push(a*P),F.push(1*o/n),M.push(A*l+_),M.push(c+y),M.push(A*u+b);for(o=0;o0){for(p=M.length/3,E.push(0),E.push(1),E.push(0),F.push(.5),F.push(.5),M.push(0+_),M.push(w+y),M.push(0+b),a=0;a<=s;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,E.push(t*l),E.push(1),E.push(t*u),F.push(f),F.push(v),M.push(t*l+_),M.push(w+y),M.push(t*u+b);for(a=0;a0){for(p=M.length/3,E.push(0),E.push(-1),E.push(0),F.push(.5),F.push(.5),M.push(0+_),M.push(0-w+y),M.push(0+b),a=0;a<=s;a++)l=Math.sin(a*x),u=Math.cos(a*x),f=.5*Math.sin(a*x)+.5,v=.5*Math.cos(a*x)+.5,E.push(i*l),E.push(-1),E.push(i*u),F.push(f),F.push(v),M.push(i*l+_),M.push(0-w+y),M.push(i*u+b);for(a=0;a0&&void 0!==arguments[0]?arguments[0]:{},t=e.lod||1,i=e.center?e.center[0]:0,r=e.center?e.center[1]:0,s=e.center?e.center[2]:0,n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);var o=e.heightSegments||18;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),(o=Math.floor(t*o))<18&&(o=18);var a=e.widthSegments||18;a<0&&(console.error("negative widthSegments not allowed - will invert"),a*=-1),(a=Math.floor(t*a))<18&&(a=18);var l,u,A,c,h,d,p,f,v,g,m,_,y,b,w=[],B=[],x=[],P=[];for(l=0;l<=o;l++)for(A=l*Math.PI/o,c=Math.sin(A),h=Math.cos(A),u=0;u<=a;u++)d=2*u*Math.PI/a,p=Math.sin(d),f=Math.cos(d)*c,v=h,g=p*c,m=1-u/a,_=l/o,B.push(f),B.push(v),B.push(g),x.push(m),x.push(_),w.push(i+n*f),w.push(r+n*v),w.push(s+n*g);for(l=0;l":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function An(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.origin||[0,0,0],i=t[0],r=t[1],s=t[2],n=e.size||1,o=[],a=[],l=e.text;le.isNumeric(l)&&(l=""+l);for(var u,A,c,h,d,p,f,v,g,m=(l||"").split("\n"),_=0,y=0,b=.04,w=0;w1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({active:!0,pos:$.vec3(),dir:$.vec3(),dist:0}),r.active=s.active,r.pos=s.pos,r.dir=s.dir,r.scene._sectionPlaneCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"SectionPlane"}},{key:"active",get:function(){return this._state.active},set:function(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dir",get:function(){return this._state.dir},set:function(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-$.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}},{key:"dist",get:function(){return this._state.dist}},{key:"flipDir",value:function(){$.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}},{key:"destroy",value:function(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),dn=$.vec4(4),pn=$.vec4(),fn=$.vec4(),vn=$.vec3([1,0,0]),gn=$.vec3([0,1,0]),mn=$.vec3([0,0,1]),_n=$.vec3(3),yn=$.vec3(3),bn=$.identityMat4(),wn=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,e,s))._parentNode=null,r._children=[],r._aabb=null,r._aabbDirty=!0,r.scene._aabbDirty=!0,r._numTriangles=0,r._scale=$.vec3(),r._quaternion=$.identityQuaternion(),r._rotation=$.vec3(),r._position=$.vec3(),r._offset=$.vec3(),r._localMatrix=$.identityMat4(),r._worldMatrix=$.identityMat4(),r._localMatrixDirty=!0,r._worldMatrixDirty=!0,s.matrix?r.matrix=s.matrix:(r.scale=s.scale,r.position=s.position,s.quaternion||(r.rotation=s.rotation)),r._isModel=s.isModel,r._isModel&&r.scene._registerModel(b(r)),r._isObject=s.isObject,r._isObject&&r.scene._registerObject(b(r)),r.origin=s.origin,r.visible=s.visible,r.culled=s.culled,r.pickable=s.pickable,r.clippable=s.clippable,r.collidable=s.collidable,r.castsShadow=s.castsShadow,r.receivesShadow=s.receivesShadow,r.xrayed=s.xrayed,r.highlighted=s.highlighted,r.selected=s.selected,r.edges=s.edges,r.colorize=s.colorize,r.opacity=s.opacity,r.offset=s.offset,s.children)for(var n=s.children,o=0,a=n.length;o1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"LambertMaterial",ambient:$.vec3([1,1,1]),color:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),r.ambient=s.ambient,r.color=s.color,r.emissive=s.emissive,r.alpha=s.alpha,r.lineWidth=s.lineWidth,r.pointSize=s.pointSize,r.backfaces=s.backfaces,r.frontface=s.frontface,r}return C(i,[{key:"type",get:function(){return"LambertMaterial"}},{key:"ambient",get:function(){return this._state.ambient},set:function(e){var t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){var t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),xn={opaque:0,mask:1,blend:2},Pn=["opaque","mask","blend"],Cn=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"MetallicMaterial",baseColor:$.vec4([1,1,1]),emissive:$.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.baseColor=s.baseColor,r.metallic=s.metallic,r.roughness=s.roughness,r.specularF0=s.specularF0,r.emissive=s.emissive,r.alpha=s.alpha,s.baseColorMap&&(r._baseColorMap=r._checkComponent("Texture",s.baseColorMap)),s.metallicMap&&(r._metallicMap=r._checkComponent("Texture",s.metallicMap)),s.roughnessMap&&(r._roughnessMap=r._checkComponent("Texture",s.roughnessMap)),s.metallicRoughnessMap&&(r._metallicRoughnessMap=r._checkComponent("Texture",s.metallicRoughnessMap)),s.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",s.emissiveMap)),s.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",s.occlusionMap)),s.alphaMap&&(r._alphaMap=r._checkComponent("Texture",s.alphaMap)),s.normalMap&&(r._normalMap=r._checkComponent("Texture",s.normalMap)),r.alphaMode=s.alphaMode,r.alphaCutoff=s.alphaCutoff,r.backfaces=s.backfaces,r.frontface=s.frontface,r.lineWidth=s.lineWidth,r.pointSize=s.pointSize,r._makeHash(),r}return C(i,[{key:"type",get:function(){return"MetallicMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"baseColor",get:function(){return this._state.baseColor},set:function(e){var t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"baseColorMap",get:function(){return this._baseColorMap}},{key:"metallic",get:function(){return this._state.metallic},set:function(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}},{key:"metallicMap",get:function(){return this._attached.metallicMap}},{key:"roughness",get:function(){return this._state.roughness},set:function(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}},{key:"roughnessMap",get:function(){return this._attached.roughnessMap}},{key:"metallicRoughnessMap",get:function(){return this._attached.metallicRoughnessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._attached.emissiveMap}},{key:"occlusionMap",get:function(){return this._attached.occlusionMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._attached.alphaMap}},{key:"normalMap",get:function(){return this._attached.normalMap}},{key:"alphaMode",get:function(){return Pn[this._state.alphaMode]},set:function(e){var t=xn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Mn={opaque:0,mask:1,blend:2},En=["opaque","mask","blend"],Fn=function(e){g(i,Ri);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({type:"SpecularMaterial",diffuse:$.vec3([1,1,1]),emissive:$.vec3([0,0,0]),specular:$.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),r.diffuse=s.diffuse,r.specular=s.specular,r.glossiness=s.glossiness,r.specularF0=s.specularF0,r.emissive=s.emissive,r.alpha=s.alpha,s.diffuseMap&&(r._diffuseMap=r._checkComponent("Texture",s.diffuseMap)),s.emissiveMap&&(r._emissiveMap=r._checkComponent("Texture",s.emissiveMap)),s.specularMap&&(r._specularMap=r._checkComponent("Texture",s.specularMap)),s.glossinessMap&&(r._glossinessMap=r._checkComponent("Texture",s.glossinessMap)),s.specularGlossinessMap&&(r._specularGlossinessMap=r._checkComponent("Texture",s.specularGlossinessMap)),s.occlusionMap&&(r._occlusionMap=r._checkComponent("Texture",s.occlusionMap)),s.alphaMap&&(r._alphaMap=r._checkComponent("Texture",s.alphaMap)),s.normalMap&&(r._normalMap=r._checkComponent("Texture",s.normalMap)),r.alphaMode=s.alphaMode,r.alphaCutoff=s.alphaCutoff,r.backfaces=s.backfaces,r.frontface=s.frontface,r.lineWidth=s.lineWidth,r.pointSize=s.pointSize,r._makeHash(),r}return C(i,[{key:"type",get:function(){return"SpecularMaterial"}},{key:"_makeHash",value:function(){var e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}},{key:"diffuse",get:function(){return this._state.diffuse},set:function(e){var t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"diffuseMap",get:function(){return this._diffuseMap}},{key:"specular",get:function(){return this._state.specular},set:function(e){var t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}},{key:"specularMap",get:function(){return this._specularMap}},{key:"specularGlossinessMap",get:function(){return this._specularGlossinessMap}},{key:"glossiness",get:function(){return this._state.glossiness},set:function(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}},{key:"glossinessMap",get:function(){return this._glossinessMap}},{key:"specularF0",get:function(){return this._state.specularF0},set:function(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}},{key:"emissive",get:function(){return this._state.emissive},set:function(e){var t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}},{key:"emissiveMap",get:function(){return this._emissiveMap}},{key:"alpha",get:function(){return this._state.alpha},set:function(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}},{key:"alphaMap",get:function(){return this._alphaMap}},{key:"normalMap",get:function(){return this._normalMap}},{key:"occlusionMap",get:function(){return this._occlusionMap}},{key:"alphaMode",get:function(){return En[this._state.alphaMode]},set:function(e){var t=Mn[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}},{key:"alphaCutoff",get:function(){return this._state.alphaCutoff},set:function(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}},{key:"backfaces",get:function(){return this._state.backfaces},set:function(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}},{key:"frontface",get:function(){return this._state.frontface?"ccw":"cw"},set:function(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}},{key:"lineWidth",get:function(){return this._state.lineWidth},set:function(e){this._state.lineWidth=e||1,this.glRedraw()}},{key:"pointSize",get:function(){return this._state.pointSize},set:function(e){this._state.pointSize=e||1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}();function kn(e,t){var i,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,s=t;if(1009===s)return e.UNSIGNED_BYTE;if(1017===s)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===s)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===s)return e.BYTE;if(1011===s)return e.SHORT;if(1012===s)return e.UNSIGNED_SHORT;if(1013===s)return e.INT;if(1014===s)return e.UNSIGNED_INT;if(1015===s)return e.FLOAT;if(1016===s)return e.HALF_FLOAT;if(1021===s)return e.ALPHA;if(1023===s)return e.RGBA;if(1024===s)return e.LUMINANCE;if(1025===s)return e.LUMINANCE_ALPHA;if(1026===s)return e.DEPTH_COMPONENT;if(1027===s)return e.DEPTH_STENCIL;if(1028===s)return e.RED;if(1022===s)return e.RGBA;if(1029===s)return e.RED_INTEGER;if(1030===s)return e.RG;if(1031===s)return e.RG_INTEGER;if(1033===s)return e.RGBA_INTEGER;if(33776===s||33777===s||33778===s||33779===s)if(3001===r){var n=Xt(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===n)return null;if(33776===s)return n.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===s)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===s)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===s)return n.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(null===(i=Xt(e,"WEBGL_compressed_texture_s3tc")))return null;if(33776===s)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===s)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===s)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===s)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===s||35841===s||35842===s||35843===s){var o=Xt(e,"WEBGL_compressed_texture_pvrtc");if(null===o)return null;if(35840===s)return o.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===s)return o.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===s)return o.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===s)return o.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===s){var a=Xt(e,"WEBGL_compressed_texture_etc1");return null!==a?a.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===s||37496===s){var l=Xt(e,"WEBGL_compressed_texture_etc");if(null===l)return null;if(37492===s)return 3001===r?l.COMPRESSED_SRGB8_ETC2:l.COMPRESSED_RGB8_ETC2;if(37496===s)return 3001===r?l.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:l.COMPRESSED_RGBA8_ETC2_EAC}if(37808===s||37809===s||37810===s||37811===s||37812===s||37813===s||37814===s||37815===s||37816===s||37817===s||37818===s||37819===s||37820===s||37821===s){var u=Xt(e,"WEBGL_compressed_texture_astc");if(null===u)return null;if(37808===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:u.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:u.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:u.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:u.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:u.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:u.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:u.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:u.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:u.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:u.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:u.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:u.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:u.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===s)return 3001===r?u.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:u.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===s){var A=Xt(e,"EXT_texture_compression_bptc");if(null===A)return null;if(36492===s)return 3001===r?A.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:A.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===s?e.UNSIGNED_INT_24_8:1e3===s?e.REPEAT:1001===s?e.CLAMP_TO_EDGE:1004===s||1005===s?e.NEAREST_MIPMAP_LINEAR:1007===s?e.LINEAR_MIPMAP_NEAREST:1008===s?e.LINEAR_MIPMAP_LINEAR:1003===s?e.NEAREST:1006===s?e.LINEAR:null}var In=new Uint8Array([0,0,0,1]),Dn=function(){function e(t){var i=t.gl,r=t.target,s=t.format,n=t.type,o=t.wrapS,a=t.wrapT,l=t.wrapR,u=t.encoding,A=t.preloadColor,c=t.premultiplyAlpha,h=t.flipY;x(this,e),this.gl=i,this.target=r||i.TEXTURE_2D,this.format=s||1023,this.type=n||1009,this.internalFormat=null,this.premultiplyAlpha=!!c,this.flipY=!!h,this.unpackAlignment=4,this.wrapS=o||1e3,this.wrapT=a||1e3,this.wrapR=l||1e3,this.encoding=u||3001,this.texture=i.createTexture(),A&&this.setPreloadColor(A),this.allocated=!0}return C(e,[{key:"setPreloadColor",value:function(e){e?(In[0]=Math.floor(255*e[0]),In[1]=Math.floor(255*e[1]),In[2]=Math.floor(255*e[2]),In[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(In[0]=0,In[1]=0,In[2]=0,In[3]=255);var t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP)for(var i=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z],r=0,s=i.length;r1&&void 0!==arguments[1]?arguments[1]:{},i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);var r=!1;i.bindTexture(this.target,this.texture);var s=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);var n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);var o=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);var a=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);var l=kn(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,l),l!==i.NEAREST_MIPMAP_NEAREST&&l!==i.LINEAR_MIPMAP_NEAREST&&l!==i.NEAREST_MIPMAP_LINEAR&&l!==i.LINEAR_MIPMAP_LINEAR||(r=!0);var u=kn(i,this.magFilter);u&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,u);var A=kn(i,this.wrapS);A&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,A);var c=kn(i,this.wrapT);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,c);var h=kn(i,this.format,this.encoding),d=kn(i,this.type),p=Sn(i,this.internalFormat,h,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(le.isArray(e))for(var f=e,v=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z],g=0,m=v.length;g1;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);var a=kn(s,this.wrapS);a&&s.texParameteri(this.target,s.TEXTURE_WRAP_S,a);var l=kn(s,this.wrapT);if(l&&s.texParameteri(this.target,s.TEXTURE_WRAP_T,l),this.type===s.TEXTURE_3D||this.type===s.TEXTURE_2D_ARRAY){var u=kn(s,this.wrapR);u&&s.texParameteri(this.target,s.TEXTURE_WRAP_R,u),s.texParameteri(this.type,s.TEXTURE_WRAP_R,u)}o?(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,Tn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,Tn(s,this.magFilter))):(s.texParameteri(this.target,s.TEXTURE_MIN_FILTER,kn(s,this.minFilter)),s.texParameteri(this.target,s.TEXTURE_MAG_FILTER,kn(s,this.magFilter)));var A=kn(s,this.format,this.encoding),c=kn(s,this.type),h=Sn(s,this.internalFormat,A,c,this.encoding,!1);s.texStorage2D(s.TEXTURE_2D,n,h,t[0].width,t[0].height);for(var d=0,p=t.length;d5&&void 0!==arguments[5]&&arguments[5];if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}var o=i;return i===e.RED&&(r===e.FLOAT&&(o=e.R32F),r===e.HALF_FLOAT&&(o=e.R16F),r===e.UNSIGNED_BYTE&&(o=e.R8)),i===e.RG&&(r===e.FLOAT&&(o=e.RG32F),r===e.HALF_FLOAT&&(o=e.RG16F),r===e.UNSIGNED_BYTE&&(o=e.RG8)),i===e.RGBA&&(r===e.FLOAT&&(o=e.RGBA32F),r===e.HALF_FLOAT&&(o=e.RGBA16F),r===e.UNSIGNED_BYTE&&(o=3001===s&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),r===e.UNSIGNED_SHORT_4_4_4_4&&(o=e.RGBA4),r===e.UNSIGNED_SHORT_5_5_5_1&&(o=e.RGB5_A1)),o!==e.R16F&&o!==e.R32F&&o!==e.RG16F&&o!==e.RG32F&&o!==e.RGBA16F&&o!==e.RGBA32F||Xt(e,"EXT_color_buffer_float"),o}function Tn(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Ln(e){if(!Rn(e.width)||!Rn(e.height)){var t=document.createElement("canvas");t.width=Un(e.width),t.height=Un(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Rn(e){return 0==(e&e-1)}function Un(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var On=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({texture:new Dn({gl:r.scene.canvas.gl}),matrix:$.identityMat4(),hasMatrix:s.translate&&(0!==s.translate[0]||0!==s.translate[1])||!!s.rotate||s.scale&&(0!==s.scale[0]||0!==s.scale[1]),minFilter:r._checkMinFilter(s.minFilter),magFilter:r._checkMagFilter(s.magFilter),wrapS:r._checkWrapS(s.wrapS),wrapT:r._checkWrapT(s.wrapT),flipY:r._checkFlipY(s.flipY),encoding:r._checkEncoding(s.encoding)}),r._src=null,r._image=null,r._translate=$.vec2([0,0]),r._scale=$.vec2([1,1]),r._rotate=$.vec2([0,0]),r._matrixDirty=!1,r.translate=s.translate,r.scale=s.scale,r.rotate=s.rotate,s.src?r.src=s.src:s.image&&(r.image=s.image),re.memory.textures++,r}return C(i,[{key:"type",get:function(){return"Texture"}},{key:"_checkMinFilter",value:function(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}},{key:"_checkMagFilter",value:function(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}},{key:"_checkWrapS",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkWrapT",value:function(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this._state.texture=new Dn({gl:this.scene.canvas.gl}),this._image?this.image=this._image:this._src&&(this.src=this._src)}},{key:"_update",value:function(){var e,t,i=this._state;this._matrixDirty&&(0===this._translate[0]&&0===this._translate[1]||(e=$.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(t=$.scalingMat4v([this._scale[0],this._scale[1],1]),e=e?$.mulMat4(e,t):t),0!==this._rotate&&(t=$.rotationMat4v(.0174532925*this._rotate,[0,0,1]),e=e?$.mulMat4(e,t):t),e&&(i.matrix=e),this._matrixDirty=!1);this.glRedraw()}},{key:"image",get:function(){return this._image},set:function(e){this._image=Ln(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}},{key:"src",get:function(){return this._src},set:function(e){this.scene.loading++,this.scene.canvas.spinner.processes++;var t=this,i=new Image;i.onload=function(){i=Ln(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}},{key:"translate",get:function(){return this._translate},set:function(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}},{key:"scale",get:function(){return this._scale},set:function(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}},{key:"rotate",get:function(){return this._rotate},set:function(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}},{key:"minFilter",get:function(){return this._state.minFilter}},{key:"magFilter",get:function(){return this._state.magFilter}},{key:"wrapS",get:function(){return this._state.wrapS}},{key:"wrapT",get:function(){return this._state.wrapT}},{key:"flipY",get:function(){return this._state.flipY}},{key:"encoding",get:function(){return this._state.encoding}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),re.memory.textures--}}]),i}(),Nn=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._state=new qt({edgeColor:$.vec3([0,0,0]),centerColor:$.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),r.edgeColor=s.edgeColor,r.centerColor=s.centerColor,r.edgeBias=s.edgeBias,r.centerBias=s.centerBias,r.power=s.power,r}return C(i,[{key:"type",get:function(){return"Fresnel"}},{key:"edgeColor",get:function(){return this._state.edgeColor},set:function(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}},{key:"centerColor",get:function(){return this._state.centerColor},set:function(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}},{key:"edgeBias",get:function(){return this._state.edgeBias},set:function(e){this._state.edgeBias=e||0,this.glRedraw()}},{key:"centerBias",get:function(){return this._state.centerBias},set:function(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}},{key:"power",get:function(){return this._state.power},set:function(e){this._state.power=null!=e?e:1,this.glRedraw()}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this._state.destroy()}}]),i}(),Qn=re.memory,Vn=$.AABB3(),Hn=function(e){g(i,Bi);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s))._state=new qt({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),r._numTriangles=0,r._edgeThreshold=s.edgeThreshold||10,r._aabb=null,r._obb=$.OBB3();var n,o=r._state,a=r.scene.canvas.gl;switch(s.primitive=s.primitive||"triangles",s.primitive){case"points":o.primitive=a.POINTS,o.primitiveName=s.primitive;break;case"lines":o.primitive=a.LINES,o.primitiveName=s.primitive;break;case"line-loop":o.primitive=a.LINE_LOOP,o.primitiveName=s.primitive;break;case"line-strip":o.primitive=a.LINE_STRIP,o.primitiveName=s.primitive;break;case"triangles":o.primitive=a.TRIANGLES,o.primitiveName=s.primitive;break;case"triangle-strip":o.primitive=a.TRIANGLE_STRIP,o.primitiveName=s.primitive;break;case"triangle-fan":o.primitive=a.TRIANGLE_FAN,o.primitiveName=s.primitive;break;default:r.error("Unsupported value for 'primitive': '"+s.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),o.primitive=a.TRIANGLES,o.primitiveName=s.primitive}if(!s.positions)return r.error("Config expected: positions"),y(r);if(!s.indices)return r.error("Config expected: indices"),y(r);var l=s.positionsDecodeMatrix;if(l);else{var u=Ii.getPositionsBounds(s.positions),A=Ii.compressPositions(s.positions,u.min,u.max);n=A.quantized,o.positionsDecodeMatrix=A.decodeMatrix,o.positionsBuf=new Dt(a,a.ARRAY_BUFFER,n,n.length,3,a.STATIC_DRAW),Qn.positions+=o.positionsBuf.numItems,$.positions3ToAABB3(s.positions,r._aabb),$.positions3ToAABB3(n,Vn,o.positionsDecodeMatrix),$.AABB3ToOBB3(Vn,r._obb)}if(s.colors){var c=s.colors.constructor===Float32Array?s.colors:new Float32Array(s.colors);o.colorsBuf=new Dt(a,a.ARRAY_BUFFER,c,c.length,4,a.STATIC_DRAW),Qn.colors+=o.colorsBuf.numItems}if(s.uv){var h=Ii.getUVBounds(s.uv),d=Ii.compressUVs(s.uv,h.min,h.max),p=d.quantized;o.uvDecodeMatrix=d.decodeMatrix,o.uvBuf=new Dt(a,a.ARRAY_BUFFER,p,p.length,2,a.STATIC_DRAW),Qn.uvs+=o.uvBuf.numItems}if(s.normals){var f=Ii.compressNormals(s.normals),v=o.compressGeometry;o.normalsBuf=new Dt(a,a.ARRAY_BUFFER,f,f.length,3,a.STATIC_DRAW,v),Qn.normals+=o.normalsBuf.numItems}var g=s.indices.constructor===Uint32Array||s.indices.constructor===Uint16Array?s.indices:new Uint32Array(s.indices);o.indicesBuf=new Dt(a,a.ELEMENT_ARRAY_BUFFER,g,g.length,1,a.STATIC_DRAW),Qn.indices+=o.indicesBuf.numItems;var m=xi(n,g,o.positionsDecodeMatrix,r._edgeThreshold);return r._edgeIndicesBuf=new Dt(a,a.ELEMENT_ARRAY_BUFFER,m,m.length,1,a.STATIC_DRAW),"triangles"===r._state.primitiveName&&(r._numTriangles=s.indices.length/3),r._buildHash(),Qn.meshes++,r}return C(i,[{key:"type",get:function(){return"VBOGeometry"}},{key:"isVBOGeometry",get:function(){return!0}},{key:"_buildHash",value:function(){var e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}},{key:"_getEdgeIndices",value:function(){return this._edgeIndicesBuf}},{key:"primitive",get:function(){return this._state.primitiveName}},{key:"aabb",get:function(){return this._aabb}},{key:"obb",get:function(){return this._obb}},{key:"numTriangles",get:function(){return this._numTriangles}},{key:"_getState",value:function(){return this._state}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this);var e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),Qn.meshes--}}]),i}(),jn={};function Gn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,r){t.src||(console.error("load3DSGeometry: Parameter expected: src"),r());var s=e.canvas.spinner;s.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),s.processes--,r());var n=jn.parse.from3DS(e).edit.objects[0].mesh,o=n.vertices,a=n.uvt,l=n.indices;s.processes--,i(le.apply(t,{primitive:"triangles",positions:o,normals:null,uv:a,indices:l}))}),(function(e){console.error("load3DSGeometry: "+e),s.processes--,r()}))}))}function zn(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((function(i,r){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),r());var s=e.canvas.spinner;s.processes++,le.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),s.processes--,r());for(var n=jn.parse.fromOBJ(e),o=jn.edit.unwrap(n.i_verts,n.c_verts,3),a=jn.edit.unwrap(n.i_norms,n.c_norms,3),l=jn.edit.unwrap(n.i_uvt,n.c_uvt,2),u=new Int32Array(n.i_verts.length),A=0;A0?a:null,autoNormals:0===a.length,uv:l,indices:u}))}),(function(e){console.error("loadOBJGeometry: "+e),s.processes--,r()}))}))}function Wn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);var r=e.zSize||1;r<0&&(console.error("negative zSize not allowed - will invert"),r*=-1);var s=e.center,n=s?s[0]:0,o=s?s[1]:0,a=s?s[2]:0,l=-t+n,u=-i+o,A=-r+a,c=t+n,h=i+o,d=r+a;return le.apply(e,{primitive:"lines",positions:[l,u,A,l,u,d,l,h,A,l,h,d,c,u,A,c,u,d,c,h,A,c,h,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Kn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Wn({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function Xn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);var i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1);for(var r=(t=t||10)/(i=i||10),s=t/2,n=[],o=[],a=0,l=0,u=-s;l<=i;l++,u+=r)n.push(-s),n.push(0),n.push(u),n.push(s),n.push(0),n.push(u),n.push(u),n.push(0),n.push(-s),n.push(u),n.push(0),n.push(s),o.push(a++),o.push(a++),o.push(a++),o.push(a++);return le.apply(e,{primitive:"lines",positions:n,indices:o})}function Yn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);var i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);var r=e.xSegments||1;r<0&&(console.error("negative xSegments not allowed - will invert"),r*=-1),r<1&&(r=1);var s=e.xSegments||1;s<0&&(console.error("negative zSegments not allowed - will invert"),s*=-1),s<1&&(s=1);var n,o,a,l,u,A,c,h=e.center,d=h?h[0]:0,p=h?h[1]:0,f=h?h[2]:0,v=t/2,g=i/2,m=Math.floor(r)||1,_=Math.floor(s)||1,y=m+1,b=_+1,w=t/m,B=i/_,x=new Float32Array(y*b*3),P=new Float32Array(y*b*3),C=new Float32Array(y*b*2),M=0,E=0;for(n=0;n65535?Uint32Array:Uint16Array)(m*_*6);for(n=0;n<_;n++)for(o=0;o0&&void 0!==arguments[0]?arguments[0]:{},t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;var i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);var r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<4&&(r=4);var s=e.tubeSegments||24;s<0&&(console.error("negative tubeSegments not allowed - will invert"),s*=-1),s<4&&(s=4);var n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);var o,a,l,u,A,c,h,d,p,f,v,g,m=e.center,_=m?m[0]:0,y=m?m[1]:0,b=m?m[2]:0,w=[],B=[],x=[],P=[];for(d=0;d<=s;d++)for(h=0;h<=r;h++)o=h/r*n,a=.785398+d/s*Math.PI*2,_=t*Math.cos(o),y=t*Math.sin(o),l=(t+i*Math.cos(a))*Math.cos(o),u=(t+i*Math.cos(a))*Math.sin(o),A=i*Math.sin(a),w.push(l+_),w.push(u+y),w.push(A+b),x.push(1-h/r),x.push(d/s),c=$.normalizeVec3($.subVec3([l,u,A],[_,y,b],[]),[]),B.push(c[0]),B.push(c[1]),B.push(c[2]);for(d=1;d<=s;d++)for(h=1;h<=r;h++)p=(r+1)*d+h-1,f=(r+1)*(d-1)+h-1,v=(r+1)*(d-1)+h,g=(r+1)*d+h,P.push(p),P.push(f),P.push(v),P.push(v),P.push(g),P.push(p);return le.apply(e,{positions:w,normals:B,uv:x,indices:P})}function Zn(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";var t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";for(var i=[],r=0;r0&&void 0!==arguments[0]?arguments[0]:{},t=e.curve.getPoints(e.divisions).map((function(e){return A(e)})).flat();return Zn({id:e.id,points:t})}jn.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},jn.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(jn.parse._buffToStr(e));window.location.href=i},jn.clone=function(e){return JSON.parse(JSON.stringify(e))},jn.bin={},jn.bin.f=new Float32Array(1),jn.bin.fb=new Uint8Array(jn.bin.f.buffer),jn.bin.rf=function(e,t){for(var i=jn.bin.f,r=jn.bin.fb,s=0;s<4;s++)r[s]=e[t+s];return i[0]},jn.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},jn.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},jn.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},jn.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},jn.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},jn.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},jn.parse={},jn.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",r=0;rs&&(s=l),un&&(n=u),Ao&&(o=A)}return{min:{x:t,y:i,z:r},max:{x:s,y:n,z:o}}};var $n=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._type=s.type||(s.src?s.src.split(".").pop():null)||"jpg",r._pos=$.vec3(s.pos||[0,0,0]),r._up=$.vec3(s.up||[0,1,0]),r._normal=$.vec3(s.normal||[0,0,1]),r._height=s.height||1,r._origin=$.vec3(),r._rtcPos=$.vec3(),r._imageSize=$.vec2(),r._texture=new On(b(r),{flipY:!0}),r._image=new Image,"jpg"!==r._type&&"png"!==r._type&&(r.error('Unsupported type - defaulting to "jpg"'),r._type="jpg"),r._node=new wn(b(r),{matrix:$.inverseMat4($.lookAtMat4v(r._pos,$.subVec3(r._pos,r._normal,$.mat4()),r._up,$.mat4())),children:[r._bitmapMesh=new nn(b(r),{scale:[1,1,1],rotation:[-90,0,0],collidable:s.collidable,pickable:s.pickable,opacity:s.opacity,clippable:s.clippable,geometry:new Ti(b(r),Yn({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ni(b(r),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:r._texture,emissiveMap:r._texture,backfaces:!0})})]}),s.image?r.image=s.image:s.src?r.src=s.src:s.imageData&&(r.imageData=s.imageData),r.scene._bitmapCreated(b(r)),r}return C(i,[{key:"visible",get:function(){return this._bitmapMesh.visible},set:function(e){this._bitmapMesh.visible=e}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}},{key:"src",get:function(){return this._image.src},set:function(e){var t=this;if(e)switch(this._image.onload=function(){t._texture.image=t._image,t._imageSize[0]=t._image.width,t._imageSize[1]=t._image.height,t._updateBitmapMeshScale()},this._image.src=e,e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}},{key:"imageData",get:function(){var e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")},set:function(e){var t=this;this._image.onload=function(){t._texture.image=image,t._imageSize[0]=image.width,t._imageSize[1]=image.height,t._updateBitmapMeshScale()},this._image.src=e}},{key:"type",get:function(){return this._type},set:function(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}},{key:"pos",get:function(){return this._pos}},{key:"normal",get:function(){return this._normal}},{key:"up",get:function(){return this._up}},{key:"height",get:function(){return this._height},set:function(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}},{key:"collidable",get:function(){return this._bitmapMesh.collidable},set:function(e){this._bitmapMesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._bitmapMesh.clippable},set:function(e){this._bitmapMesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._bitmapMesh.pickable},set:function(e){this._bitmapMesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._bitmapMesh.opacity},set:function(e){this._bitmapMesh.opacity=e}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._bitmapDestroyed(this)}},{key:"_updateBitmapMeshScale",value:function(){var e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}]),i}(),eo=$.OBB3(),to=$.OBB3(),io=$.OBB3(),ro=function(){function e(t,i,r,s,n,o){var a=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,l=arguments.length>7&&void 0!==arguments[7]?arguments[7]:0;x(this,e),this.model=t,this.object=null,this.parent=null,this.transform=n,this.textureSet=o,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=i,this.obb=null,this._aabbLocal=null,this._aabbWorld=$.AABB3(),this._aabbWorldDirty=!1,this.layer=a,this.portionId=l,this._color=new Uint8Array([r[0],r[1],r[2],s]),this._colorize=new Uint8Array([r[0],r[1],r[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,n&&n._addMesh(this)}return C(e,[{key:"_sceneModelDirty",value:function(){this._aabbWorldDirty=!0,this.layer.aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbDirty=!0,this.entity&&this.entity._transformDirty()}},{key:"_updateMatrix",value:function(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}},{key:"_finalize",value:function(e){this.layer.initFlags(this.portionId,e,this._transparent)}},{key:"_finalize2",value:function(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}},{key:"_setVisible",value:function(e){this.layer.setVisible(this.portionId,e,this._transparent)}},{key:"_setColor",value:function(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}},{key:"_setColorize",value:function(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}},{key:"_setOpacity",value:function(e,t){var i=e<255,r=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),r&&this.layer.setTransparent(this.portionId,t,i)}},{key:"_setOffset",value:function(e){this.layer.setOffset(this.portionId,e)}},{key:"_setHighlighted",value:function(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}},{key:"_setXRayed",value:function(e){this.layer.setXRayed(this.portionId,e,this._transparent)}},{key:"_setSelected",value:function(e){this.layer.setSelected(this.portionId,e,this._transparent)}},{key:"_setEdges",value:function(e){this.layer.setEdges(this.portionId,e,this._transparent)}},{key:"_setClippable",value:function(e){this.layer.setClippable(this.portionId,e,this._transparent)}},{key:"_setCollidable",value:function(e){this.layer.setCollidable(this.portionId,e)}},{key:"_setPickable",value:function(e){this.layer.setPickable(this.portionId,e,this._transparent)}},{key:"_setCulled",value:function(e){this.layer.setCulled(this.portionId,e,this._transparent)}},{key:"canPickTriangle",value:function(){return!1}},{key:"drawPickTriangles",value:function(e,t){}},{key:"pickTriangleSurface",value:function(e){}},{key:"precisionRayPickSurface",value:function(e,t,i,r){return!!this.layer.precisionRayPickSurface&&this.layer.precisionRayPickSurface(this.portionId,e,t,i,r)}},{key:"canPickWorldPos",value:function(){return!0}},{key:"drawPickDepths",value:function(e){this.model.drawPickDepths(e)}},{key:"drawPickNormals",value:function(e){this.model.drawPickNormals(e)}},{key:"delegatePickedEntity",value:function(){return this.parent}},{key:"getEachVertex",value:function(e){this.layer.getEachVertex(this.portionId,e)}},{key:"aabb",get:function(){if(this._aabbWorldDirty){if($.AABB3ToOBB3(this._aabbLocal,eo),this.transform?($.transformOBB3(this.transform.worldMatrix,eo,to),$.transformOBB3(this.model.worldMatrix,to,io),$.OBB3ToAABB3(io,this._aabbWorld)):($.transformOBB3(this.model.worldMatrix,eo,to),$.OBB3ToAABB3(to,this._aabbWorld)),this.origin){var e=this.origin;this._aabbWorld[0]+=e[0],this._aabbWorld[1]+=e[1],this._aabbWorld[2]+=e[2],this._aabbWorld[3]+=e[0],this._aabbWorld[4]+=e[1],this._aabbWorld[5]+=e[2]}this._aabbWorldDirty=!1}return this._aabbWorld},set:function(e){this._aabbLocal=e}},{key:"_destroy",value:function(){this.model.scene._renderer.putPickID(this.pickId)}}]),e}(),so=new(function(){function e(){x(this,e),this._uint8Arrays={},this._float32Arrays={}}return C(e,[{key:"_clear",value:function(){this._uint8Arrays={},this._float32Arrays={}}},{key:"getUInt8Array",value:function(e){var t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}},{key:"getFloat32Array",value:function(e){var t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}}]),e}()),no=0;function oo(){return no++,so}var ao={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},lo=new Float32Array([1,1,1,1]),uo=new Float32Array([0,0,0,1]),Ao=$.vec4(),co=$.vec3(),ho=$.vec3(),po=$.mat4(),fo=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=r.instancing,n=void 0!==s&&s,o=r.edges,a=void 0!==o&&o;x(this,e),this._scene=t,this._withSAO=i,this._instancing=n,this._edges=a,this._hash=this._getHash(),this._matricesUniformBlockBufferBindingPoint=0,this._matricesUniformBlockBuffer=this._scene.canvas.gl.createBuffer(),this._matricesUniformBlockBufferData=new Float32Array(96),this._vaoCache=new WeakMap,this._allocate()}return C(e,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"_buildShader",value:function(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}},{key:"_buildVertexShader",value:function(){return[""]}},{key:"_buildFragmentShader",value:function(){return[""]}},{key:"_addMatricesUniformBlockLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return e.push("uniform Matrices {"),e.push(" mat4 worldMatrix;"),e.push(" mat4 viewMatrix;"),e.push(" mat4 projMatrix;"),e.push(" mat4 positionsDecodeMatrix;"),t&&(e.push(" mat4 worldNormalMatrix;"),e.push(" mat4 viewNormalMatrix;")),e.push("};"),e}},{key:"_addRemapClipPosLines",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return e.push("uniform vec2 drawingBufferSize;"),e.push("uniform vec2 pickClipPos;"),e.push("vec4 remapClipPos(vec4 clipPos) {"),e.push(" clipPos.xy /= clipPos.w;"),1===t?e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"):e.push(" clipPos.xy = (clipPos.xy - pickClipPos) * (drawingBufferSize / float(".concat(t,"));")),e.push(" clipPos.xy *= clipPos.w;"),e.push(" return clipPos;"),e.push("}"),e}},{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"setSectionPlanesStateUniforms",value:function(e){var t=this._scene,i=t.canvas.gl,r=e.model,s=e.layerIndex,n=t._sectionPlanesState.getNumAllocatedSectionPlanes(),o=t._sectionPlanesState.sectionPlanes.length;if(n>0){var a=t._sectionPlanesState.sectionPlanes,l=s*o,u=r.renderFlags;t.crossSections&&(i.uniform4fv(this._uSliceColor,t.crossSections.sliceColor),i.uniform1f(this._uSliceThickness,t.crossSections.sliceThickness));for(var A=0;A0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(var a=0,l=e._sectionPlanesState.getNumAllocatedSectionPlanes();a3&&void 0!==arguments[3]?arguments[3]:{},s=r.colorUniform,n=void 0!==s&&s,o=r.incrementDrawState,a=void 0!==o&&o,l=bt.MAX_TEXTURE_IMAGE_UNITS,u=this._scene,A=u.canvas.gl,c=t._state,h=t.model,d=c.textureSet,p=c.origin,f=c.positionsDecodeMatrix,v=u._lightsState,g=u.pointsMaterial,m=h.scene.camera,_=m.viewNormalMatrix,y=m.project,b=e.pickViewMatrix||m.viewMatrix,w=h.position,B=h.rotationMatrix,x=h.rotationMatrixConjugate,P=h.worldNormalMatrix;if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),this._vaoCache.has(t)?A.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(c));var C=0,M=16;this._matricesUniformBlockBufferData.set(x,0);var E=0!==p[0]||0!==p[1]||0!==p[2],F=0!==w[0]||0!==w[1]||0!==w[2];if(E||F){var k=co;if(E){var I=$.transformPoint3(B,p,ho);k[0]=I[0],k[1]=I[1],k[2]=I[2]}else k[0]=0,k[1]=0,k[2]=0;k[0]+=w[0],k[1]+=w[1],k[2]+=w[2],this._matricesUniformBlockBufferData.set(Le(b,k,po),C+=M)}else this._matricesUniformBlockBufferData.set(b,C+=M);if(this._matricesUniformBlockBufferData.set(e.pickProjMatrix||y.matrix,C+=M),this._matricesUniformBlockBufferData.set(f,C+=M),this._matricesUniformBlockBufferData.set(P,C+=M),this._matricesUniformBlockBufferData.set(_,C+=M),A.bindBuffer(A.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),A.bufferData(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,A.DYNAMIC_DRAW),A.bindBufferBase(A.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer),A.uniform1i(this._uRenderPass,i),this.setSectionPlanesStateUniforms(t),u.logarithmicDepthBufferEnabled){if(this._uLogDepthBufFC){var D=2/(Math.log(e.pickZFar+1)/Math.LN2);A.uniform1f(this._uLogDepthBufFC,D)}this._uZFar&&A.uniform1f(this._uZFar,u.camera.project.far)}if(this._uPickInvisible&&A.uniform1i(this._uPickInvisible,e.pickInvisible),this._uPickZNear&&A.uniform1f(this._uPickZNear,e.pickZNear),this._uPickZFar&&A.uniform1f(this._uPickZFar,e.pickZFar),this._uPickClipPos&&A.uniform2fv(this._uPickClipPos,e.pickClipPos),this._uDrawingBufferSize&&A.uniform2f(this._uDrawingBufferSize,A.drawingBufferWidth,A.drawingBufferHeight),this._uUVDecodeMatrix&&A.uniformMatrix3fv(this._uUVDecodeMatrix,!1,c.uvDecodeMatrix),this._uIntensityRange&&g.filterIntensity&&A.uniform2f(this._uIntensityRange,g.minIntensity,g.maxIntensity),this._uPointSize&&A.uniform1f(this._uPointSize,g.pointSize),this._uNearPlaneHeight){var S="ortho"===u.camera.projection?1:A.drawingBufferHeight/(2*Math.tan(.5*u.camera.perspective.fov*Math.PI/180));A.uniform1f(this._uNearPlaneHeight,S)}if(d){var T=d.colorTexture,L=d.metallicRoughnessTexture,R=d.emissiveTexture,U=d.normalsTexture,O=d.occlusionTexture;this._uColorMap&&T&&(this._program.bindTexture(this._uColorMap,T.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uMetallicRoughMap&&L&&(this._program.bindTexture(this._uMetallicRoughMap,L.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uEmissiveMap&&R&&(this._program.bindTexture(this._uEmissiveMap,R.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uNormalMap&&U&&(this._program.bindTexture(this._uNormalMap,U.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l),this._uAOMap&&O&&(this._program.bindTexture(this._uAOMap,O.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l)}if(v.reflectionMaps.length>0&&v.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,v.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),v.lightMaps.length>0&&v.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,v.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++),this._withSAO){var N=u.sao,Q=N.possible;if(Q){var V=A.drawingBufferWidth,H=A.drawingBufferHeight;Ao[0]=V,Ao[1]=H,Ao[2]=N.blendCutoff,Ao[3]=N.blendFactor,A.uniform4fv(this._uSAOParams,Ao),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%l,e.bindTexture++}}if(n){var j=this._edges?"edgeColor":"fillColor",G=this._edges?"edgeAlpha":"fillAlpha";if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_XRAYED")]){var z=u.xrayMaterial._state,W=z[j],K=z[G];A.uniform4f(this._uColor,W[0],W[1],W[2],K)}else if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_HIGHLIGHTED")]){var X=u.highlightMaterial._state,Y=X[j],J=X[G];A.uniform4f(this._uColor,Y[0],Y[1],Y[2],J)}else if(i===ao["".concat(this._edges?"EDGES":"SILHOUETTE","_SELECTED")]){var Z=u.selectedMaterial._state,q=Z[j],ee=Z[G];A.uniform4f(this._uColor,q[0],q[1],q[2],ee)}else A.uniform4fv(this._uColor,this._edges?uo:lo)}this._draw({state:c,frameCtx:e,incrementDrawState:a}),A.bindVertexArray(null)}}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null,re.memory.programs--}}]),e}(),vo=function(e){g(i,fo);var t=_(i);function i(e,r){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=s.edges,o=void 0!==n&&n;return x(this,i),t.call(this,e,r,{instancing:!1,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,s=e.incrementDrawState;if(this._edges)t.drawElements(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0);else{var n=r.pickElementsCount||i.indicesBuf.numItems,o=r.pickElementsOffset?r.pickElementsOffset*i.indicesBuf.itemByteSize:0;t.drawElements(t.TRIANGLES,n,i.indicesBuf.itemType,o),s&&r.drawElements++}}}]),i}(),go=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t=this._scene,i=t._sectionPlanesState,r=t._lightsState,s=i.getNumAllocatedSectionPlanes()>0,n=[];n.push("#version 300 es"),n.push("// Triangles batching draw vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in float flags;"),t.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("uniform vec4 lightAmbient;");for(var o=0,a=r.lights.length;o= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),s&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;")),n.push("out vec4 vColor;"),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),t.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching draw fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),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(newColor.rgb * ambient, 1.0);")):r.push(" outColor = newColor;"),r.push("}"),r}}]),i}(),mo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching flat-shading draw vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._lightsState,i=e._sectionPlanesState,r=i.getNumAllocatedSectionPlanes()>0,s=[];if(s.push("#version 300 es"),s.push("// Triangles batching flat-shading draw fragment shader"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&(s.push("in float isPerspective;"),s.push("uniform float logDepthBufFC;"),s.push("in float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4 uSAOParams;"),s.push("const float packUpscale = 256. / 255.;"),s.push("const float unpackDownScale = 255. / 256.;"),s.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),s.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push(" return dot( v, unPackFactors );"),s.push("}")),r){s.push("in vec4 vWorldPosition;"),s.push("in float vFlags;");for(var n=0,o=i.getNumAllocatedSectionPlanes();n> 16 & 0xF) == 1;"),s.push(" if (clippable) {"),s.push(" float dist = 0.0;");for(var A=0,c=i.getNumAllocatedSectionPlanes();A sliceThickness) { "),s.push(" discard;"),s.push(" }"),s.push(" if (dist > 0.0) { "),s.push(" newColor = sliceColor;"),s.push(" }"),s.push("}")}s.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),s.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),s.push("float lambertian = 1.0;"),s.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),s.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),s.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var h=0,d=t.lights.length;h0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, color.a ));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching silhouette fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s){for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var o=0,a=r.getNumAllocatedSectionPlanes();o sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = newColor;"),n.push("}"),n}}]),i}(),yo=function(e){g(i,vo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!1,edges:!0})}return C(i)}(),bo=function(e){g(i,yo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesEmphasisRenderer 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),wo=function(e){g(i,yo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry edges 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),Bo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vPickColor; "),r.push("}"),r}}]),i}(),xo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),this._addRemapClipPosLines(i),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick depth 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 float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),Po=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec3 worldNormal = octDecode(normal.xy); "),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick normals 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Co=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching occlusion vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles batching occlusion fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Mo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching depth fragment shader"),r.push("precision highp float;"),r.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),r.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),r.push("}"),r}}]),i}(),Eo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Fo=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry shadow vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 outColor;"),i.push("void main(void) {"),i.push(" int colorFlag = int(flags) & 0xF;"),i.push(" bool visible = (colorFlag > 0);"),i.push(" bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push(" if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}}]),i}(),ko=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,r=t.getNumAllocatedSectionPlanes()>0,s=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Triangles batching quality draw vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),r&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),s&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&n.push("worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),n.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),n.push("vFragDepth = 1.0 + clipPos.w;")),r&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),s&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,r=e._lightsState,s=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Triangles batching quality draw fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),o.push("uniform sampler2D uAOMap;"),o.push("in vec4 vViewPosition;"),o.push("in vec3 vViewNormal;"),o.push("in vec4 vColor;"),o.push("in vec2 vUV;"),o.push("in vec2 vMetallicRoughness;"),r.lightMaps.length>0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),r.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=r.lights.length;a0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = sRGBToLinear(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(o.push(" vec3 irradiance = sRGBToLinear(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),s){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb(vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=r.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching pick flat normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Triangles batching pick flat normals 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("in vec4 vWorldPosition;"),i){r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Do=function(e){g(i,vo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Triangles batching color texture vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._lightsState,r=e._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Triangles batching color texture fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),e.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),n.push("uniform sampler2D uColorMap;"),this._withSAO&&(n.push("uniform sampler2D uOcclusionTexture;"),n.push("uniform vec4 uSAOParams;"),n.push("const float packUpscale = 256. / 255.;"),n.push("const float unpackDownScale = 255. / 256.;"),n.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),n.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),n.push("float unpackRGBToFloat( const in vec4 v ) {"),n.push(" return dot( v, unPackFactors );"),n.push("}")),n.push("uniform float gammaFactor;"),n.push("vec4 linearToLinear( in vec4 value ) {"),n.push(" return value;"),n.push("}"),n.push("vec4 sRGBToLinear( in vec4 value ) {"),n.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),n.push("}"),n.push("vec4 gammaToLinear( in vec4 value) {"),n.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),n.push("}"),t&&(n.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),n.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),n.push("}")),s){n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;");for(var o=0,a=r.getNumAllocatedSectionPlanes();o> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;");for(var c=0,h=r.getNumAllocatedSectionPlanes();c sliceThickness) { "),n.push(" discard;"),n.push(" }"),n.push(" if (dist > 0.0) { "),n.push(" newColor = sliceColor;"),n.push(" }"),n.push("}")}n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),n.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),n.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),n.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );");for(var d=0,p=i.lights.length;d0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),No=$.vec3(),Qo=$.vec3(),Vo=$.vec3(),Ho=$.vec3(),jo=$.mat4(),Go=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=No;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Qo;if(l){var m=Vo;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,jo),(f=Ho)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElements(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0),a.edgeIndicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),zo=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new Bo(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new xo(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Oo(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Go(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new go(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new go(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new mo(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new mo(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Do(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Do(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new ko(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ko(this._scene,!0)),this._pbrRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new _o(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Mo(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Eo(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new bo(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new wo(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Bo(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Po(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Io(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new xo(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Co(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Fo(this._scene)),this._shadowRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Go(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Oo(this._scene)),this._snapInitRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Wo={};var Ko=65536,Xo=5e6,Yo=function(){function e(){x(this,e)}return C(e,[{key:"doublePrecisionEnabled",get:function(){return $.getDoublePrecisionEnabled()},set:function(e){$.setDoublePrecisionEnabled(e)}},{key:"maxDataTextureHeight",get:function(){return Ko},set:function(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),Ko=e}},{key:"maxGeometryBatchSize",get:function(){return Xo},set:function(e){e<1e5?e=1e5:e>5e6&&(e=5e6),Xo=e}}]),e}(),Jo=new Yo,Zo=C((function e(){x(this,e),this.maxVerts=Jo.maxGeometryBatchSize,this.maxIndices=3*Jo.maxGeometryBatchSize,this.positions=[],this.colors=[],this.uv=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.offsets=[],this.indices=[],this.edgeIndices=[]})),qo=$.mat4(),$o=$.mat4();function ea(e,t,i){for(var r=e.length,s=new Uint16Array(r),n=t[0],o=t[1],a=t[2],l=t[3]-n,u=t[4]-o,A=t[5]-a,c=65525,h=c/l,d=c/u,p=c/A,f=function(e){return e>=0?e:0},v=0;v=0?1:-1),o=(1-Math.abs(r))*(s>=0?1:-1),r=n,s=o}return new Int8Array([Math[t](127.5*r+(r<0?-1:0)),Math[i](127.5*s+(s<0?-1:0))])}function ra(e){var t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;var r=1-Math.abs(t)-Math.abs(i);r<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));var s=Math.sqrt(t*t+i*i+r*r);return[t/s,i/s,r/s]}var sa=$.mat4(),na=$.mat4(),oa=$.vec4([0,0,0,1]),aa=$.vec3(),la=$.vec3(),ua=$.vec3(),Aa=$.vec3(),ca=$.vec3(),ha=$.vec3(),da=$.vec3(),pa=function(){function e(t){var i,r,s;x(this,e),console.info("Creating VBOBatchingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesBatchingLayer"+(t.solid?"-solid":"-surface")+(t.autoNormals?"-autonormals":"-normals")+(t.textureSet&&t.textureSet.colorTexture?"-colorTexture":"")+(t.textureSet&&t.textureSet.metallicRoughnessTexture?"-metallicRoughnessTexture":""),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(s=Wo[r])||(s=new zo(i),Wo[r]=s,s._compile(),s.eagerCreateRenders(),i.on("compile",(function(){s._compile(),s.eagerCreateRenders()})),i.on("destroyed",(function(){delete Wo[r],s._destroy()}))),s),this._buffer=new Zo(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({origin:$.vec3(),positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,uvBuf:null,metallicRoughnessBuf:null,flagsBuf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,textureSet:t.textureSet,pbrSupported:!1}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix&&(this._state.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)),t.uvDecodeMatrix?(this._state.uvDecodeMatrix=$.mat3(t.uvDecodeMatrix),this._preCompressedUVsExpected=!0):this._preCompressedUVsExpected=!1,t.origin&&this._state.origin.set(t.origin),this.solid=!!t.solid}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)for(var C=0,M=o.length;C0){var E=sa;g?$.inverseMat4($.transposeMat4(g,na),E):$.identityMat4(E,E),function(e,t,i,r,s){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}var o,a,l,u,A,c=new Float32Array([0,0,0,0]),h=new Float32Array([0,0,0,0]);for(A=0;Au&&(a=o,u=l),(l=n(h,ra(o=ia(h,"floor","ceil"))))>u&&(a=o,u=l),(l=n(h,ra(o=ia(h,"ceil","ceil"))))>u&&(a=o,u=l),r[s+A+0]=a[0],r[s+A+1]=a[1],r[s+A+2]=0}(E,n,n.length,y.normals,y.normals.length)}if(u)for(var F=0,k=u.length;F0)for(var V=0,H=a.length;V0)for(var j=0,G=l.length;j0){var r=this._state.positionsDecodeMatrix?new Uint16Array(i.positions):ea(i.positions,this._modelAABB,this._state.positionsDecodeMatrix=$.mat4());if(e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,r,r.length,3,t.STATIC_DRAW),this.model.scene.pickSurfacePrecisionEnabled)for(var s=0,n=this._portions.length;s0){var u=new Int8Array(i.normals);e.normalsBuf=new Dt(t,t.ARRAY_BUFFER,u,i.normals.length,3,t.STATIC_DRAW,!0)}if(i.colors.length>0){var A=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,A,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.uv.length>0)if(e.uvDecodeMatrix){e.uvBuf=new Dt(t,t.ARRAY_BUFFER,i.uv,i.uv.length,2,t.STATIC_DRAW,!1)}else{var c=Ii.getUVBounds(i.uv),h=Ii.compressUVs(i.uv,c.min,c.max),d=h.quantized;e.uvDecodeMatrix=$.mat3(h.decodeMatrix),e.uvBuf=new Dt(t,t.ARRAY_BUFFER,d,d.length,2,t.STATIC_DRAW,!1)}if(i.metallicRoughness.length>0){var p=new Uint8Array(i.metallicRoughness);e.metallicRoughnessBuf=new Dt(t,t.ARRAY_BUFFER,p,i.metallicRoughness.length,2,t.STATIC_DRAW,!1)}if(i.positions.length>0){var f=i.positions.length/3,v=new Float32Array(f);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,v,v.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var g=new Uint8Array(i.pickColors);e.pickColorsBuf=new Dt(t,t.ARRAY_BUFFER,g,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var m=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,m,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var _=new Uint32Array(i.indices);e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,_,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){var y=new Uint32Array(i.edgeIndices);e.edgeIndicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,y,i.edgeIndices.length,1,t.STATIC_DRAW)}this._state.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&e.textureSet&&e.textureSet.colorTexture&&e.textureSet.metallicRoughnessTexture),this._state.colorTextureSupported=!!e.uvBuf&&!!e.textureSet&&!!e.textureSet.colorTexture,this._buffer=null,this._finalized=!0}}},{key:"isEmpty",value:function(){return!this._state.indicesBuf}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=e,r=this._portions[i],s=4*r.vertsBaseIndex,n=4*r.numVerts,o=this._scratchMemory.getUInt8Array(n),a=t[0],l=t[1],u=t[2],A=t[3],c=0;c3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var s,n,o=e,a=this._portions[o],l=a.vertsBaseIndex,u=a.numVerts,A=l,c=u,h=!!(t&Qe),d=!!(t&ze),p=!!(t&We),f=!!(t&Ke),v=!!(t&Xe),g=!!(t&He),m=!!(t&Ve);s=!h||m||d||p&&!this.model.scene.highlightMaterial.glowThrough||f&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!h||m?ao.NOT_RENDERED:f?ao.SILHOUETTE_SELECTED:p?ao.SILHOUETTE_HIGHLIGHTED:d?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var _=0;_=!h||m?ao.NOT_RENDERED:f?ao.EDGES_SELECTED:p?ao.EDGES_HIGHLIGHTED:d?ao.EDGES_XRAYED:v?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED;var y=h&&!m&&g?ao.PICK:ao.NOT_RENDERED,b=t&je?1:0;if(r){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var w=A,B=A+c;wg)&&(g=x,r.set(m),s&&$.triangleNormal(d,p,f,s),v=!0)}}return v&&s&&($.transformVec3(this.model.worldNormalMatrix,s,s),$.normalizeVec3(s)),v}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}]),e}(),fa=function(e){g(i,fo);var t=_(i);function i(e,r){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=s.edges,o=void 0!==n&&n;return x(this,i),t.call(this,e,r,{instancing:!0,edges:o})}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,s=e.incrementDrawState;this._edges?t.drawElementsInstanced(t.LINES,i.edgeIndicesBuf.numItems,i.edgeIndicesBuf.itemType,0,i.numInstances):(t.drawElementsInstanced(t.TRIANGLES,i.indicesBuf.numItems,i.indicesBuf.itemType,0,i.numInstances),s&&r.drawElements++)}}]),i}(),va=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e,t,i,r=this._scene,s=r._sectionPlanesState,n=r._lightsState,o=s.getNumAllocatedSectionPlanes()>0,a=[];for(a.push("#version 300 es"),a.push("// Instancing geometry drawing vertex shader"),a.push("uniform int renderPass;"),a.push("in vec3 position;"),a.push("in vec2 normal;"),a.push("in vec4 color;"),a.push("in float flags;"),r.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),r.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("out float vFragDepth;"),a.push("bool isPerspectiveMatrix(mat4 m) {"),a.push(" return (m[2][3] == - 1.0);"),a.push("}"),a.push("out float isPerspective;")),a.push("uniform vec4 lightAmbient;"),e=0,t=n.lights.length;e= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),a.push(" }"),a.push(" return normalize(v);"),a.push("}"),o&&(a.push("out vec4 vWorldPosition;"),a.push("out float vFlags;")),a.push("out vec4 vColor;"),a.push("void main(void) {"),a.push("int colorFlag = int(flags) & 0xF;"),a.push("if (colorFlag != renderPass) {"),a.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),a.push("} else {"),a.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),a.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),r.entityOffsetsEnabled&&a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = viewMatrix * worldPosition; "),a.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),a.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),a.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),e=0,t=n.lights.length;e0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry 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("}")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),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(newColor.rgb * ambient, 1.0);")):r.push(" outColor = newColor;"),r.push("}"),r}}]),i}(),ga=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry flat-shading drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=i._lightsState,n=r.getNumAllocatedSectionPlanes()>0,o=[];if(o.push("#version 300 es"),o.push("// Instancing geometry flat-shading drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),i.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),n){o.push("in vec4 vWorldPosition;"),o.push("in float vFlags;");for(var a=0,l=r.getNumAllocatedSectionPlanes();a> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var A=0,c=r.getNumAllocatedSectionPlanes();A sliceThickness) { "),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" newColor = sliceColor;"),o.push(" }"),o.push("}")}for(o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;"),o.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),o.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),o.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=s.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// Instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 color;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 silhouetteColor;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vColor = vec4(silhouetteColor.r, silhouetteColor.g, silhouetteColor.b, min(silhouetteColor.a, float(color.a) / 255.0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing fill 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o sliceThickness) { "),r.push(" discard;"),r.push(" }"),r.push(" if (dist > 0.0) { "),r.push(" newColor = sliceColor;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = newColor;"),r.push("}"),r}}]),i}(),_a=function(e){g(i,fa);var t=_(i);function i(e,r){return x(this,i),t.call(this,e,r,{instancing:!0,edges:!0})}return C(i)}(),ya=function(e){g(i,_a);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesEmphasisRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesEmphasisRenderer 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),ba=function(e){g(i,_a);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!1})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// EdgesColorRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeFlag = int(flags) >> 8 & 0xF;"),i.push("if (edgeFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// EdgesColorRenderer 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),wa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry picking vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 pickColor;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry picking fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vPickColor; "),r.push("}"),r}}]),i}(),Ba=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push(" vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry depth 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 float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),xa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec2 normal;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("in vec4 modelNormalMatrixCol0;"),i.push("in vec4 modelNormalMatrixCol1;"),i.push("in vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push(" vWorldNormal = worldNormal;"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outNormal = ivec4(vWorldNormal * float(".concat($.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Pa=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesInstancingOcclusionRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}}]),i}(),Ca=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry depth drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Instancing geometry depth drawing fragment shader"),n.push("precision highp float;"),n.push("precision highp int;"),i.logarithmicDepthBufferEnabled&&(n.push("in float isPerspective;"),n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),n.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),n.push("}"),n}}]),i}(),Ma=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec3 normal;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i,!0),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Ea=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),Fa={3e3:"linearToLinear",3001:"sRGBToLinear"},ka=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=e._lightsState,r=t.getNumAllocatedSectionPlanes()>0,s=t.clippingCaps,n=[];return n.push("#version 300 es"),n.push("// Instancing geometry quality drawing vertex shader"),n.push("uniform int renderPass;"),n.push("in vec3 position;"),n.push("in vec3 normal;"),n.push("in vec4 color;"),n.push("in vec2 uv;"),n.push("in vec2 metallicRoughness;"),n.push("in float flags;"),e.entityOffsetsEnabled&&n.push("in vec3 offset;"),n.push("in vec4 modelMatrixCol0;"),n.push("in vec4 modelMatrixCol1;"),n.push("in vec4 modelMatrixCol2;"),n.push("in vec4 modelNormalMatrixCol0;"),n.push("in vec4 modelNormalMatrixCol1;"),n.push("in vec4 modelNormalMatrixCol2;"),this._addMatricesUniformBlockLines(n,!0),n.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("out float isPerspective;")),n.push("vec3 octDecode(vec2 oct) {"),n.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push(" if (v.z < 0.0) {"),n.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push(" }"),n.push(" return normalize(v);"),n.push("}"),n.push("out vec4 vViewPosition;"),n.push("out vec3 vViewNormal;"),n.push("out vec4 vColor;"),n.push("out vec2 vUV;"),n.push("out vec2 vMetallicRoughness;"),i.lightMaps.length>0&&n.push("out vec3 vWorldNormal;"),r&&(n.push("out vec4 vWorldPosition;"),n.push("out float vFlags;"),s&&n.push("out vec4 vClipPosition;")),n.push("void main(void) {"),n.push("int colorFlag = int(flags) & 0xF;"),n.push("if (colorFlag != renderPass) {"),n.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push(" worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 1.0);"),n.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(n.push("vFragDepth = 1.0 + clipPos.w;"),n.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),r&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags = flags;"),s&&n.push("vClipPosition = clipPos;")),n.push("vViewPosition = viewPosition;"),n.push("vViewNormal = viewNormal;"),n.push("vColor = color;"),n.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),n.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&n.push("vWorldNormal = worldNormal.xyz;"),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,r=e._lightsState,s=i.getNumAllocatedSectionPlanes()>0,n=i.clippingCaps,o=[];o.push("#version 300 es"),o.push("// Instancing geometry quality drawing fragment shader"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&(o.push("in float isPerspective;"),o.push("uniform float logDepthBufFC;"),o.push("in float vFragDepth;")),o.push("uniform sampler2D uColorMap;"),o.push("uniform sampler2D uMetallicRoughMap;"),o.push("uniform sampler2D uEmissiveMap;"),o.push("uniform sampler2D uNormalMap;"),this._withSAO&&(o.push("uniform sampler2D uOcclusionTexture;"),o.push("uniform vec4 uSAOParams;"),o.push("const float packUpscale = 256. / 255.;"),o.push("const float unpackDownScale = 255. / 256.;"),o.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),o.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),o.push("float unpackRGBToFloat( const in vec4 v ) {"),o.push(" return dot( v, unPackFactors );"),o.push("}")),r.reflectionMaps.length>0&&o.push("uniform samplerCube reflectionMap;"),r.lightMaps.length>0&&o.push("uniform samplerCube lightMap;"),o.push("uniform vec4 lightAmbient;");for(var a=0,l=r.lights.length;a0&&o.push("in vec3 vWorldNormal;"),this._addMatricesUniformBlockLines(o,!0),o.push("#define PI 3.14159265359"),o.push("#define RECIPROCAL_PI 0.31830988618"),o.push("#define RECIPROCAL_PI2 0.15915494"),o.push("#define EPSILON 1e-6"),o.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),o.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),o.push(" vec3 texel = texture( uNormalMap, uv ).xyz;"),o.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),o.push(" return normalize(surf_norm );"),o.push(" }"),o.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),o.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),o.push(" vec2 st0 = dFdx( uv.st );"),o.push(" vec2 st1 = dFdy( uv.st );"),o.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),o.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),o.push(" vec3 N = normalize( surf_norm );"),o.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),o.push(" mat3 tsn = mat3( S, T, N );"),o.push(" return normalize( tsn * mapN );"),o.push("}"),o.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),o.push(" return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),o.push("}"),o.push("struct IncidentLight {"),o.push(" vec3 color;"),o.push(" vec3 direction;"),o.push("};"),o.push("struct ReflectedLight {"),o.push(" vec3 diffuse;"),o.push(" vec3 specular;"),o.push("};"),o.push("struct Geometry {"),o.push(" vec3 position;"),o.push(" vec3 viewNormal;"),o.push(" vec3 worldNormal;"),o.push(" vec3 viewEyeDir;"),o.push("};"),o.push("struct Material {"),o.push(" vec3 diffuseColor;"),o.push(" float specularRoughness;"),o.push(" vec3 specularColor;"),o.push(" float shine;"),o.push("};"),o.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),o.push(" float r = ggxRoughness + 0.0001;"),o.push(" return (2.0 / (r * r) - 2.0);"),o.push("}"),o.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float maxMIPLevelScalar = float( maxMIPLevel );"),o.push(" float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),o.push(" return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),o.push("}"),r.reflectionMaps.length>0&&(o.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),o.push(" float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),o.push(" vec3 envMapColor = "+Fa[r.reflectionMaps[0].encoding]+"(texture(reflectionMap, reflectVec, mipLevel)).rgb;"),o.push(" return envMapColor;"),o.push("}")),o.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),o.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),o.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),o.push("}"),o.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" return 1.0 / ( gl * gv );"),o.push("}"),o.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),o.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),o.push(" return 0.5 / max( gv + gl, EPSILON );"),o.push("}"),o.push("float D_GGX(const in float alpha, const in float dotNH) {"),o.push(" float a2 = ( alpha * alpha );"),o.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),o.push(" return RECIPROCAL_PI * a2 / ( denom * denom);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float alpha = ( roughness * roughness );"),o.push(" vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),o.push(" float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),o.push(" float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),o.push(" float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),o.push(" float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),o.push(" vec3 F = F_Schlick( specularColor, dotLH );"),o.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),o.push(" float D = D_GGX( alpha, dotNH );"),o.push(" return F * (G * D);"),o.push("}"),o.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),o.push(" float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),o.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),o.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),o.push(" vec4 r = roughness * c0 + c1;"),o.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),o.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),o.push(" return specularColor * AB.x + AB.y;"),o.push("}"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&(o.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),r.lightMaps.length>0&&(o.push(" vec3 irradiance = "+Fa[r.lightMaps[0].encoding]+"(texture(lightMap, geometry.worldNormal)).rgb;"),o.push(" irradiance *= PI;"),o.push(" vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),r.reflectionMaps.length>0&&(o.push(" vec3 reflectVec = reflect(geometry.viewEyeDir, geometry.viewNormal);"),o.push(" reflectVec = inverseTransformDirection(reflectVec, viewMatrix);"),o.push(" float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),o.push(" vec3 radiance = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),o.push(" vec3 specularBRDFContrib = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),o.push(" reflectedLight.specular += radiance * specularBRDFContrib;")),o.push("}")),o.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.push(" float dotNL = saturate(dot(geometry.viewNormal, incidentLight.direction));"),o.push(" vec3 irradiance = dotNL * incidentLight.color * PI;"),o.push(" reflectedLight.diffuse += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),o.push(" reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),o.push("}"),o.push("out vec4 outColor;"),o.push("void main(void) {"),s){o.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),o.push(" if (clippable) {"),o.push(" float dist = 0.0;");for(var h=0,d=i.getNumAllocatedSectionPlanes();h (0.002 * vClipPosition.w)) {"),o.push(" discard;"),o.push(" }"),o.push(" if (dist > 0.0) { "),o.push(" outColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&o.push(" gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push(" return;"),o.push("}")):(o.push(" if (dist > 0.0) { "),o.push(" discard;"),o.push(" }")),o.push("}")}o.push("IncidentLight light;"),o.push("Material material;"),o.push("Geometry geometry;"),o.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),o.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),o.push("float opacity = float(vColor.a) / 255.0;"),o.push("vec3 baseColor = rgb;"),o.push("float specularF0 = 1.0;"),o.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),o.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),o.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),o.push("vec4 colorTexel = sRGBToLinear(texture(uColorMap, vUV));"),o.push("baseColor *= colorTexel.rgb;"),o.push("vec3 metalRoughTexel = texture(uMetallicRoughMap, vUV).rgb;"),o.push("metallic *= metalRoughTexel.b;"),o.push("roughness *= metalRoughTexel.g;"),o.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition.xyz, normalize(vViewNormal), vUV );"),o.push("material.diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),o.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),o.push("material.specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),o.push("geometry.position = vViewPosition.xyz;"),o.push("geometry.viewNormal = -normalize(viewNormal);"),o.push("geometry.viewEyeDir = normalize(vViewPosition.xyz);"),r.lightMaps.length>0&&o.push("geometry.worldNormal = normalize(vWorldNormal);"),(r.lightMaps.length>0||r.reflectionMaps.length>0)&&o.push("computePBRLightMapping(geometry, material, reflectedLight);");for(var p=0,f=r.lights.length;p0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry normals vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),this._addRemapClipPosLines(i,3),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&i.push("out float vFlags;"),i.push("out vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&i.push("vFlags = flags;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Batched geometry normals 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("in vec4 vWorldPosition;"),i){r.push("in float vFlags;");for(var s=0;s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),r.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),r.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),r.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),r.push("}"),r}}]),i}(),Da=function(e){g(i,fa);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){var e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry drawing vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in vec2 uv;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),i.push("uniform mat3 uvDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vViewPosition;"),i.push("out vec4 vColor;"),i.push("out vec2 vUV;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vViewPosition = viewPosition;"),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),i.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i.gammaOutput,s=i._sectionPlanesState,n=i._lightsState,o=s.getNumAllocatedSectionPlanes()>0,a=[];if(a.push("#version 300 es"),a.push("// Instancing geometry drawing fragment shader"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),i.logarithmicDepthBufferEnabled&&(a.push("in float isPerspective;"),a.push("uniform float logDepthBufFC;"),a.push("in float vFragDepth;")),a.push("uniform sampler2D uColorMap;"),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4 uSAOParams;"),a.push("const float packUpscale = 256. / 255.;"),a.push("const float unpackDownScale = 255. / 256.;"),a.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),a.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBToFloat( const in vec4 v ) {"),a.push(" return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push(" return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push(" return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push(" return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),r&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push(" return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),o){a.push("in vec4 vWorldPosition;"),a.push("in float vFlags;");for(var l=0,u=s.getNumAllocatedSectionPlanes();l> 16 & 0xF) == 1;"),a.push(" if (clippable) {"),a.push(" float dist = 0.0;");for(var c=0,h=s.getNumAllocatedSectionPlanes();c sliceThickness) { "),a.push(" discard;"),a.push(" }"),a.push(" if (dist > 0.0) { "),a.push(" newColor = sliceColor;"),a.push(" }"),a.push("}")}for(a.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),a.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),a.push("float lambertian = 1.0;"),a.push("vec3 xTangent = dFdx( vViewPosition.xyz );"),a.push("vec3 yTangent = dFdy( vViewPosition.xyz );"),a.push("vec3 viewNormal = normalize( cross( xTangent, yTangent ) );"),e=0,t=n.lights.length;e0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Na=$.vec3(),Qa=$.vec3(),Va=$.vec3(),Ha=$.vec3(),ja=$.mat4(),Ga=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Na;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Qa;if(l){var m=$.transformPoint3(A,l,Va);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,ja),(f=Ha)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.edgeIndicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.edgeIndicesBuf.numItems,a.edgeIndicesBuf.itemType,0,a.numInstances),a.edgeIndicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),za=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._pbrRenderer&&!this._pbrRenderer.getValid()&&(this._pbrRenderer.destroy(),this._pbrRenderer=null),this._pbrRendererWithSAO&&!this._pbrRendererWithSAO.getValid()&&(this._pbrRendererWithSAO.destroy(),this._pbrRendererWithSAO=null),this._colorTextureRenderer&&!this._colorTextureRenderer.getValid()&&(this._colorTextureRenderer.destroy(),this._colorTextureRenderer=null),this._colorTextureRendererWithSAO&&!this._colorTextureRendererWithSAO.getValid()&&(this._colorTextureRendererWithSAO.destroy(),this._colorTextureRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new wa(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new Ba(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new Oa(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ga(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new va(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new va(this._scene,!0)),this._colorRendererWithSAO}},{key:"flatColorRenderer",get:function(){return this._flatColorRenderer||(this._flatColorRenderer=new ga(this._scene,!1)),this._flatColorRenderer}},{key:"flatColorRendererWithSAO",get:function(){return this._flatColorRendererWithSAO||(this._flatColorRendererWithSAO=new ga(this._scene,!0)),this._flatColorRendererWithSAO}},{key:"pbrRenderer",get:function(){return this._pbrRenderer||(this._pbrRenderer=new ka(this._scene,!1)),this._pbrRenderer}},{key:"pbrRendererWithSAO",get:function(){return this._pbrRendererWithSAO||(this._pbrRendererWithSAO=new ka(this._scene,!0)),this._pbrRendererWithSAO}},{key:"colorTextureRenderer",get:function(){return this._colorTextureRenderer||(this._colorTextureRenderer=new Da(this._scene,!1)),this._colorTextureRenderer}},{key:"colorTextureRendererWithSAO",get:function(){return this._colorTextureRendererWithSAO||(this._colorTextureRendererWithSAO=new Da(this._scene,!0)),this._colorTextureRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ma(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new Ca(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new Ma(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new ya(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new ba(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new wa(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new xa(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new Ia(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Ba(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Pa(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new Ea(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Oa(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Ga(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._pbrRenderer&&this._pbrRenderer.destroy(),this._pbrRendererWithSAO&&this._pbrRendererWithSAO.destroy(),this._colorTextureRenderer&&this._colorTextureRenderer.destroy(),this._colorTextureRendererWithSAO&&this._colorTextureRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Wa={};var Ka=new Uint8Array(4),Xa=new Float32Array(1),Ya=$.vec4([0,0,0,1]),Ja=new Float32Array(3),Za=$.vec3(),qa=$.vec3(),$a=$.vec3(),el=$.vec3(),tl=$.vec3(),il=$.vec3(),rl=$.vec3(),sl=new Float32Array(4),nl=function(){function e(t){var i,r,s;x(this,e),console.info("Creating VBOInstancingTrianglesLayer"),this.model=t.model,this.sortId="TrianglesInstancingLayer"+(t.solid?"-solid":"-surface")+(t.normals?"-normals":"-autoNormals"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(s=Wa[r])||(s=new za(i),Wa[r]=s,s._compile(),s.eagerCreateRenders(),i.on("compile",(function(){s._compile(),s.eagerCreateRenders()})),i.on("destroyed",(function(){delete Wa[r],s._destroy()}))),s),this._aabb=$.collapseAABB3(),this._state=new qt({numInstances:0,obb:$.OBB3(),origin:$.vec3(),geometry:t.geometry,textureSet:t.textureSet,pbrSupported:!1,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,modelNormalMatrixCol0Buf:null,modelNormalMatrixCol1Buf:null,modelNormalMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrix=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&this._state.origin.set(t.origin),this._finalized=!1,this.solid=!!t.solid,this.numIndices=t.geometry.numIndices}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){e.colorsBuf=new Dt(r,r.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,r.DYNAMIC_DRAW,!1),this._colors=[]}if(this._metallicRoughness.length>0){var o=new Uint8Array(this._metallicRoughness);e.metallicRoughnessBuf=new Dt(r,r.ARRAY_BUFFER,o,this._metallicRoughness.length,2,r.STATIC_DRAW,!1)}if(n>0){e.flagsBuf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(n),n,1,r.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){e.offsetsBuf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,r.DYNAMIC_DRAW,!1),this._offsets=[]}if(t.positionsCompressed&&t.positionsCompressed.length>0){e.positionsBuf=new Dt(r,r.ARRAY_BUFFER,t.positionsCompressed,t.positionsCompressed.length,3,r.STATIC_DRAW,!1),e.positionsDecodeMatrix=$.mat4(t.positionsDecodeMatrix)}if(t.colorsCompressed&&t.colorsCompressed.length>0){var a=new Uint8Array(t.colorsCompressed);e.colorsBuf=new Dt(r,r.ARRAY_BUFFER,a,a.length,4,r.STATIC_DRAW,!1)}if(t.uvCompressed&&t.uvCompressed.length>0){var l=t.uvCompressed;e.uvDecodeMatrix=t.uvDecodeMatrix,e.uvBuf=new Dt(r,r.ARRAY_BUFFER,l,l.length,2,r.STATIC_DRAW,!1)}if(t.indices&&t.indices.length>0&&(e.indicesBuf=new Dt(r,r.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.indices),t.indices.length,1,r.STATIC_DRAW),e.numIndices=t.indices.length),"triangles"!==t.primitive&&"solid"!==t.primitive&&"surface"!==t.primitive||(e.edgeIndicesBuf=new Dt(r,r.ELEMENT_ARRAY_BUFFER,new Uint32Array(t.edgeIndices),t.edgeIndices.length,1,r.STATIC_DRAW)),this._modelMatrixCol0.length>0){var u=!1;e.modelMatrixCol0Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,r.STATIC_DRAW,u),e.modelMatrixCol1Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,r.STATIC_DRAW,u),e.modelMatrixCol2Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,r.STATIC_DRAW,u),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],e.normalsBuf&&(e.modelNormalMatrixCol0Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,r.STATIC_DRAW,u),e.modelNormalMatrixCol1Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,r.STATIC_DRAW,u),e.modelNormalMatrixCol2Buf=new Dt(r,r.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,r.STATIC_DRAW,u),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[])}if(this._pickColors.length>0){e.pickColorsBuf=new Dt(r,r.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,r.STATIC_DRAW,!1),this._pickColors=[]}e.pbrSupported=!!(e.metallicRoughnessBuf&&e.uvBuf&&e.normalsBuf&&i&&i.colorTexture&&i.metallicRoughnessTexture),e.colorTextureSupported=!!e.uvBuf&&!!i&&!!i.colorTexture,this._state.geometry=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ka[0]=t[0],Ka[1]=t[1],Ka[2]=t[2],Ka[3]=t[3],this._state.colorsBuf&&this._state.colorsBuf.setData(Ka,4*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&Qe),s=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!r||u||s||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!r||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:s?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!r||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:s?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(r&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?1:0)<<16,Xa[0]=A,this._state.flagsBuf&&this._state.flagsBuf.setData(Xa,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Ja[0]=t[0],Ja[1]=t[1],Ja[2]=t[2],this._state.offsetsBuf&&this._state.offsetsBuf.setData(Ja,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"getEachVertex",value:function(e,t){if(!this.model.scene.pickSurfacePrecisionEnabled)return!1;var i=this._state,r=i.geometry,s=this._portions[e];if(s)for(var n=r.quantizedPositions,o=i.origin,a=s.offset,l=o[0]+a[0],u=o[1]+a[1],A=o[2]+a[2],c=Ya,h=s.matrix,d=this.model.sceneModelMatrix,p=i.positionsDecodeMatrix,f=0,v=n.length;fm)&&(m=C,r.set(_),s&&$.triangleNormal(p,f,v,s),g=!0)}}return g&&s&&($.transformVec3(a.normalMatrix,s,s),$.transformVec3(this.model.worldNormalMatrix,s,s),$.normalizeVec3(s)),g}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy(),this._state=null}}]),e}(),ol=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,s=e.incrementDrawState;t.drawElements(t.LINES,i.indicesBuf.numItems,i.indicesBuf.itemType,0),s&&r.drawElements++}}]),i}(),al=function(e){g(i,ol);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines batching color 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),ll=function(e){g(i,ol);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines batching silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines batching silhouette 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = color;"),r.push("}"),r}}]),i}(),ul=$.vec3(),Al=$.vec3(),cl=$.vec3(),hl=$.vec3(),dl=$.mat4(),pl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=ul;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=Al;if(l){var m=cl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,dl),(f=hl)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBO SnapBatchingDepthBufInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),fl=$.vec3(),vl=$.vec3(),gl=$.vec3(),ml=$.vec3(),_l=$.mat4(),yl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=fl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=vl;if(l){var m=gl;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,_l),(f=ml)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElements(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0),a.indicesBuf.unbind()):o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapBatchingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),bl=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new al(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ll(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new pl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new yl(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),wl={};var Bl=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;x(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.offsets=[],this.indices=[]})),xl=function(){function e(t){var i,r,s;x(this,e),console.info("Creating VBOBatchingLinesLayer"),this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(s=wl[r])||(s=new bl(i),wl[r]=s,s._compile(),i.on("compile",(function(){s._compile()})),i.on("destroyed",(function(){delete wl[r],s._destroy()}))),s),this.model=t.model,this._buffer=new Bl(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,indicesBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._numVerts=0,this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var r=new Uint16Array(i.positions);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}else{var s=ea(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.DYNAMIC_DRAW,!1)}if(i.colors.length>0){var o=i.colors.length/4,a=new Float32Array(o);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var l=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,l,i.offsets.length,3,t.DYNAMIC_DRAW)}if(i.indices.length>0){var u=new Uint32Array(i.indices);e.indicesBuf=new Dt(t,t.ELEMENT_ARRAY_BUFFER,u,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,!0)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,r=4*this._portions[i],s=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(s),o=t[0],a=t[1],l=t[2],u=t[3],A=0;A3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var s,n,o=2*e,a=this._portions[o],l=this._portions[o+1],u=a,A=l,c=!!(t&Qe),h=!!(t&ze),d=!!(t&We),p=!!(t&Ke),f=!!(t&He),v=!!(t&Ve);s=!c||v||h||d&&!this.model.scene.highlightMaterial.glowThrough||p&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!c||v?ao.NOT_RENDERED:p?ao.SILHOUETTE_SELECTED:d?ao.SILHOUETTE_HIGHLIGHTED:h?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var g=c&&!v&&f?ao.PICK:ao.NOT_RENDERED,m=t&je?1:0;if(r){this._deferredFlagValues||(this._deferredFlagValues=new Float32Array(this._numVerts));for(var _=u,y=u+A;_0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing color vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),i.push("in vec4 color;"),i.push("in float flags;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("if (colorFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Lines instancing color fragment shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return this._withSAO?(n.push(" float viewportWidth = uSAOParams[0];"),n.push(" float viewportHeight = uSAOParams[1];"),n.push(" float blendCutoff = uSAOParams[2];"),n.push(" float blendFactor = uSAOParams[3];"),n.push(" vec2 uv = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),n.push(" float ambient = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture(uOcclusionTexture, uv))) * blendFactor;"),n.push(" outColor = vec4(vColor.rgb * ambient, vColor.a);")):n.push(" outColor = vColor;"),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),Ml=function(e){g(i,Pl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Lines instancing silhouette vertex shader"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(i),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),i.push("if (silhouetteFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Lines instancing silhouette 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = color;"),r.push("}"),r}}]),i}(),El=$.vec3(),Fl=$.vec3(),kl=$.vec3();$.vec3();var Il=$.mat4(),Dl=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.canvas.gl,o=s.camera,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=El;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Fl;if(l){var g=$.transformPoint3(A,l,kl);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Il),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),a.indicesBuf.bind(),n.drawElementsInstanced(n.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind(),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Sl=$.vec3(),Tl=$.vec3(),Ll=$.vec3();$.vec3();var Rl=$.mat4(),Ul=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Sl;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Tl;if(l){var g=$.transformPoint3(A,l,Ll);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Rl),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),"edge"===e.snapMode?(a.indicesBuf.bind(),o.drawElementsInstanced(o.LINES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),a.indicesBuf.unbind()):o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Ol=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapRenderer||(this._snapRenderer=new Ul(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Cl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ml(this._scene)),this._silhouetteRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Dl(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new Ul(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Nl={};var Ql=new Uint8Array(4),Vl=new Float32Array(1),Hl=new Float32Array(3),jl=new Float32Array(4),Gl=function(){function e(t){var i,r,s;x(this,e),console.info("VBOInstancingLinesLayer"),this.model=t.model,this.material=t.material,this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(s=Nl[r])||(s=new Ol(i),Nl[r]=s,s._compile(),i.on("compile",(function(){s._compile()})),i.on("destroyed",(function(){delete Nl[r],s._destroy()}))),s),this._aabb=$.collapseAABB3(),this._state=new qt({obb:$.OBB3(),numInstances:0,origin:null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,positionsBuf:null,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,t.origin&&(this._state.origin=$.vec3(t.origin)),this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){this._state.colorsBuf=new Dt(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,!1),this._colors=[]}if(s>0){this._state.flagsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(s),s,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){this._state.offsetsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(i.colorsCompressed&&i.colorsCompressed.length>0){var n=new Uint8Array(i.colorsCompressed);t.colorsBuf=new Dt(e,e.ARRAY_BUFFER,n,n.length,4,e.STATIC_DRAW,!1)}if(i.positionsCompressed&&i.positionsCompressed.length>0){t.positionsBuf=new Dt(e,e.ARRAY_BUFFER,i.positionsCompressed,i.positionsCompressed.length,3,e.STATIC_DRAW,!1),t.positionsDecodeMatrix=$.mat4(i.positionsDecodeMatrix)}if(i.indices&&i.indices.length>0&&(t.indicesBuf=new Dt(e,e.ELEMENT_ARRAY_BUFFER,new Uint32Array(i.indices),i.indices.length,1,e.STATIC_DRAW),t.numIndices=i.indices.length),this._modelMatrixCol0.length>0){var o=!1;this._state.modelMatrixCol0Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol1Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,o),this._state.modelMatrixCol2Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,o),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._state.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Ql[0]=t[0],Ql[1]=t[1],Ql[2]=t[2],Ql[3]=t[3],this._state.colorsBuf.setData(Ql,4*e,4)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&Qe),s=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!r||u||s||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!r||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:s?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!r||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:s?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(r&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?255:0)<<16,Vl[0]=A,this._state.flagsBuf.setData(Vl,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Hl[0]=t[0],Hl[1]=t[1],Hl[2]=t[2],this._state.offsetsBuf.setData(Hl,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;jl[0]=t[0],jl[1]=t[4],jl[2]=t[8],jl[3]=t[12],this._state.modelMatrixCol0Buf.setData(jl,i),jl[0]=t[1],jl[1]=t[5],jl[2]=t[9],jl[3]=t[13],this._state.modelMatrixCol1Buf.setData(jl,i),jl[0]=t[2],jl[1]=t[6],jl[2]=t[10],jl[3]=t[14],this._state.modelMatrixCol2Buf.setData(jl,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){var e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.destroy()}}]),e}(),zl=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_draw",value:function(e){var t=this._scene.canvas.gl,i=e.state,r=e.frameCtx,s=e.incrementDrawState;t.drawArrays(t.POINTS,0,i.positionsBuf.numItems),s&&r.drawArrays++}}]),i}(),Wl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{incrementDrawState:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial,r=[];return r.push("#version 300 es"),r.push("// Points batching color vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("in float flags;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),i.filterIntensity&&r.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),i.filterIntensity&&(r.push("float intensity = float(color.a) / 255.0;"),r.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {")),r.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push("worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),i.filterIntensity&&r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching color 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),Kl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching silhouette vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),this._addMatricesUniformBlockLines(r),r.push("uniform vec4 color;"),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),r.push("if (silhouetteFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points batching silhouette vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),s){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("outColor = color;"),n.push("}"),n}}]),i}(),Xl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching pick mesh vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 pickColor;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vPickColor;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),r.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("gl_PointSize += 10.0;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching pick mesh vertex 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vPickColor; "),r.push("}"),r}}]),i}(),Yl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batched pick depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vViewPosition;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vViewPosition = viewPosition;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("gl_PointSize += 10.0;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batched pick depth 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),Jl=function(e){g(i,zl);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points batching occlusion vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push(" } else {"),r.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push(" gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push(" }"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points batching occlusion fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push(" }")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),r.push("}"),r}}]),i}(),Zl=$.vec3(),ql=$.vec3(),$l=$.vec3(),eu=$.vec3(),tu=$.mat4(),iu=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=Zl;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=ql;if(l){var m=$l;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,tu),(f=eu)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),ru=$.vec3(),su=$.vec3(),nu=$.vec3(),ou=$.vec3(),au=$.mat4(),lu=function(e){g(i,fo);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f,v=ru;if(v[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,v[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,v[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(v[0]),e.snapPickCoordinateScale[1]=$.safeInv(v[1]),e.snapPickCoordinateScale[2]=$.safeInv(v[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var g=su;if(l){var m=nu;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],p=Le(d,g,au),(f=ou)[0]=n.eye[0]-g[0],f[1]=n.eye[1]-g[1],f[2]=n.eye[2]-g[2],e.snapPickOrigin[0]=g[0],e.snapPickOrigin[1]=g[1],e.snapPickOrigin[2]=g[2]}else p=d,f=n.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,v),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var _=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,_+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,_+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,_+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var y=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,y),this.setSectionPlanesStateUniforms(t),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this._uCameraEyeRtc=e.getLocation("uCameraEyeRtc"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0;e.pointsMaterial._state;var i=[];return i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// VBOBatchingPointsSnapRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),uu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Wl(this._scene)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Kl(this._scene)),this._silhouetteRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Xl(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Yl(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new Jl(this._scene)),this._occlusionRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new iu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new lu(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Au={};var cu=C((function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:5e6;x(this,e),t>5e6&&(t=5e6),this.maxVerts=t,this.maxIndices=3*t,this.positions=[],this.colors=[],this.intensities=[],this.pickColors=[],this.offsets=[]})),hu=function(){function e(t){x(this,e),console.info("Creating VBOBatchingPointsLayer"),this.model=t.model,this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._renderers=function(e){var t=e.id,i=Au[t];return i||(i=new uu(e),Au[t]=i,i._compile(),e.on("compile",(function(){i._compile()})),e.on("destroyed",(function(){delete Au[t],i._destroy()}))),i}(t.model.scene),this._buffer=new cu(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new qt({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,positionsDecodeMatrix:$.mat4(),origin:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=$.collapseAABB3(),this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1,t.positionsDecodeMatrix?(this._state.positionsDecodeMatrix.set(t.positionsDecodeMatrix),this._preCompressedPositionsExpected=!0):this._preCompressedPositionsExpected=!1,t.origin&&(this._state.origin=$.vec3(t.origin))}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0)if(this._preCompressedPositionsExpected){var r=new Uint16Array(i.positions);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,r,i.positions.length,3,t.STATIC_DRAW)}else{var s=ea(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new Dt(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){var n=new Uint8Array(i.colors);e.colorsBuf=new Dt(t,t.ARRAY_BUFFER,n,i.colors.length,4,t.STATIC_DRAW,!1)}if(i.positions.length>0){var o=i.positions.length/3,a=new Float32Array(o);e.flagsBuf=new Dt(t,t.ARRAY_BUFFER,a,a.length,1,t.DYNAMIC_DRAW,!1)}if(i.pickColors.length>0){var l=new Uint8Array(i.pickColors);e.pickColorsBuf=new Dt(t,t.ARRAY_BUFFER,l,i.pickColors.length,4,t.STATIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){var u=new Float32Array(i.offsets);e.offsetsBuf=new Dt(t,t.ARRAY_BUFFER,u,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized"}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";for(var i=2*e,r=4*this._portions[i],s=4*this._portions[i+1],n=this._scratchMemory.getUInt8Array(s),o=t[0],a=t[1],l=t[2],u=0;u0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing color vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),r.push("in vec4 color;"),r.push("in float flags;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),i.filterIntensity&&r.push("uniform vec2 intensityRange;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),i.filterIntensity&&(r.push("float intensity = float(color.a) / 255.0;"),r.push("if (intensity < intensityRange[0] || intensity > intensityRange[1]) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {")),r.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),r.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, 1.0);"),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),i.filterIntensity&&r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing color 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vColor;"),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),fu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"drawLayer",value:function(e,t,r){f(w(i.prototype),"drawLayer",this).call(this,e,t,r,{colorUniform:!0})}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing silhouette vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 color;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),r.push("uniform vec4 silhouetteColor;"),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vColor;"),r.push("void main(void) {"),r.push("int silhouetteFlag = int(flags) >> 4 & 0xF;"),r.push("if (silhouetteFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("vColor = vec4(float(silhouetteColor.r) / 255.0, float(silhouetteColor.g) / 255.0, float(silhouetteColor.b) / 255.0, float(color.a) / 255.0);"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing silhouette 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vColor;"),r.push("}"),r}}]),i}(),vu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing pick mesh vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 pickColor;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vPickColor;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),r.push(" vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),r.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing pick mesh 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("outColor = vPickColor; "),r.push("}"),r}}]),i}(),gu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing pick depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),r.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(r),this._addRemapClipPosLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("out vec4 vViewPosition;"),r.push("void main(void) {"),r.push("int pickFlag = int(flags) >> 12 & 0xF;"),r.push("if (pickFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push(" vFlags = flags;")),r.push(" vViewPosition = viewPosition;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),r.push("gl_Position = remapClipPos(clipPos);"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = remapClipPos(clipPos);"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing pick depth 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),r.push("uniform float pickZNear;"),r.push("uniform float pickZFar;"),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),r.push(" outColor = packDepth(zNormalizedDepth); "),r.push("}"),r}}]),i}(),mu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing occlusion vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in vec4 color;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push(" vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Points instancing occlusion vertex 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0;s 1.0) {"),r.push(" discard;"),r.push(" }")),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),r.push("}")}return r.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}}]),i}(),_u=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=e.pointsMaterial._state,r=[];return r.push("#version 300 es"),r.push("// Points instancing depth vertex shader"),r.push("uniform int renderPass;"),r.push("in vec3 position;"),e.entityOffsetsEnabled&&r.push("in vec3 offset;"),r.push("in float flags;"),r.push("in vec4 modelMatrixCol0;"),r.push("in vec4 modelMatrixCol1;"),r.push("in vec4 modelMatrixCol2;"),this._addMatricesUniformBlockLines(r),r.push("uniform float pointSize;"),i.perspectivePoints&&r.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),r.push("out float vFragDepth;")),t&&(r.push("out vec4 vWorldPosition;"),r.push("out float vFlags;")),r.push("void main(void) {"),r.push("int colorFlag = int(flags) & 0xF;"),r.push("if (colorFlag != renderPass) {"),r.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),r.push("} else {"),r.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),r.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&r.push(" worldPosition.xyz = worldPosition.xyz + offset;"),r.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(r.push("vWorldPosition = worldPosition;"),r.push("vFlags = flags;")),r.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&r.push("vFragDepth = 1.0 + clipPos.w;"),r.push("gl_Position = clipPos;"),i.perspectivePoints?(r.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),r.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),r.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):r.push("gl_PointSize = pointSize;"),r.push("}"),r.push("}"),r}},{key:"_buildFragmentShader",value:function(){var e,t,i=this._scene,r=i._sectionPlanesState,s=r.getNumAllocatedSectionPlanes()>0,n=[];if(n.push("#version 300 es"),n.push("// Points instancing depth vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("#endif"),i.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("in float vFragDepth;")),s)for(n.push("in vec4 vWorldPosition;"),n.push("in float vFlags;"),e=0,t=r.getNumAllocatedSectionPlanes();e 1.0) {"),n.push(" discard;"),n.push(" }")),s){for(n.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),n.push(" if (clippable) {"),n.push(" float dist = 0.0;"),e=0,t=r.getNumAllocatedSectionPlanes();e 0.0) { discard; }"),n.push("}")}return n.push(" outColor = packDepthToRGBA( gl_FragCoord.z); "),i.logarithmicDepthBufferEnabled&&n.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),n.push("}"),n}}]),i}(),yu=function(e){g(i,du);var t=_(i);function i(){return x(this,i),t.apply(this,arguments)}return C(i,[{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// Instancing geometry shadow drawing vertex shader"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in vec4 color;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),this._addMatricesUniformBlockLines(i),i.push("uniform float pointSize;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("void main(void) {"),i.push("int colorFlag = int(flags) & 0xF;"),i.push("bool visible = (colorFlag > 0);"),i.push("bool transparent = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags = flags;")),i.push(" gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// Instancing geometry depth 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("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),i){r.push("in vec4 vWorldPosition;"),r.push("in float vFlags;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 1.0) {"),r.push(" discard;"),r.push(" }"),i){r.push(" bool clippable = (int(vFlags) >> 16 & 0xF) == 1;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { discard; }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push("gl_FragDepth = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),r.push("}"),r}}]),i}(),bu=$.vec3(),wu=$.vec3(),Bu=$.vec3();$.vec3();var xu=$.mat4(),Pu=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.canvas.gl,o=s.camera,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||o.viewMatrix;this._vaoCache.has(t)?n.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=bu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=wu;if(l){var g=$.transformPoint3(A,l,Bu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,xu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;n.uniform2fv(this.uVectorA,e.snapVectorA),n.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),n.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),n.uniform3fv(this._uCoordinateScaler,f),n.uniform1i(this._uRenderPass,i),n.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(o.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),n.bindBuffer(n.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),n.bufferData(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,n.DYNAMIC_DRAW),n.bindBufferBase(n.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);n.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisor(this._aModelMatrixCol0.location,1),n.vertexAttribDivisor(this._aModelMatrixCol1.location,1),n.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisor(this._aFlags.location,1)),n.drawArraysInstanced(n.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisor(this._aModelMatrixCol0.location,0),n.vertexAttribDivisor(this._aModelMatrixCol1.location,0),n.vertexAttribDivisor(this._aModelMatrixCol2.location,0),this._aFlags&&n.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&n.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthBufInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec4 pickColor;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("out float vFlags;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vWorldPosition = worldPosition;"),t&&i.push(" vFlags = flags;"),i.push("vPickColor = pickColor;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Points instancing pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, -layerNumber);"),i.push("outNormal = ivec4(1.0, 1.0, 1.0, 1.0);"),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Cu=$.vec3(),Mu=$.vec3(),Eu=$.vec3();$.vec3();var Fu=$.mat4(),ku=function(e){g(i,fo);var t=_(i);function i(e){return x(this,i),t.call(this,e,!1,{instancing:!0})}return C(i,[{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=t.aabb,d=e.pickViewMatrix||n.viewMatrix;this._vaoCache.has(t)?o.bindVertexArray(this._vaoCache.get(t)):this._vaoCache.set(t,this._makeVAO(a));var p,f=Cu;if(f[0]=$.safeInv(h[3]-h[0])*$.MAX_INT,f[1]=$.safeInv(h[4]-h[1])*$.MAX_INT,f[2]=$.safeInv(h[5]-h[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(f[0]),e.snapPickCoordinateScale[1]=$.safeInv(f[1]),e.snapPickCoordinateScale[2]=$.safeInv(f[2]),l||0!==u[0]||0!==u[1]||0!==u[2]){var v=Mu;if(l){var g=$.transformPoint3(A,l,Eu);v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=u[0],v[1]+=u[1],v[2]+=u[2],p=Le(d,v,Fu),e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else p=d,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;o.uniform2fv(this.uVectorA,e.snapVectorA),o.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),o.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),o.uniform3fv(this._uCoordinateScaler,f),o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);var m=0;this._matricesUniformBlockBufferData.set(c,0),this._matricesUniformBlockBufferData.set(p,m+=16),this._matricesUniformBlockBufferData.set(n.projMatrix,m+=16),this._matricesUniformBlockBufferData.set(a.positionsDecodeMatrix,m+=16),o.bindBuffer(o.UNIFORM_BUFFER,this._matricesUniformBlockBuffer),o.bufferData(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferData,o.DYNAMIC_DRAW),o.bindBufferBase(o.UNIFORM_BUFFER,this._matricesUniformBlockBufferBindingPoint,this._matricesUniformBlockBuffer);var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_),this.setSectionPlanesStateUniforms(t),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),o.vertexAttribDivisor(this._aModelMatrixCol0.location,1),o.vertexAttribDivisor(this._aModelMatrixCol1.location,1),o.vertexAttribDivisor(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(a.flagsBuf),o.vertexAttribDivisor(this._aFlags.location,1),o.drawArraysInstanced(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),o.vertexAttribDivisor(this._aModelMatrixCol0.location,0),o.vertexAttribDivisor(this._aModelMatrixCol1.location,0),o.vertexAttribDivisor(this._aModelMatrixCol2.location,0),o.vertexAttribDivisor(this._aFlags.location,0),this._aOffset&&o.vertexAttribDivisor(this._aOffset.location,0)}}},{key:"_allocate",value:function(){f(w(i.prototype),"_allocate",this).call(this);var e=this._program;this._uLogDepthBufFC=e.getLocation("logDepthBufFC"),this.uVectorA=e.getLocation("snapVectorA"),this.uInverseVectorAB=e.getLocation("snapInvVectorAB"),this._uLayerNumber=e.getLocation("layerNumber"),this._uCoordinateScaler=e.getLocation("coordinateScaler")}},{key:"_bindProgram",value:function(){this._program.bind()}},{key:"_buildVertexShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];return i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("in vec3 position;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("in float flags;"),i.push("in vec4 modelMatrixCol0;"),i.push("in vec4 modelMatrixCol1;"),i.push("in vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),this._addMatricesUniformBlockLines(i),i.push("uniform vec2 snapVectorA;"),i.push("uniform vec2 snapInvVectorAB;"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - snapVectorA.x) * snapInvVectorAB.x;"),i.push(" float y = (clipPos.y - snapVectorA.y) * snapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out float vFlags;")),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int pickFlag = int(flags) >> 12 & 0xF;"),i.push("if (pickFlag != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push(" vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push(" worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags = flags;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// SnapInstancingDepthRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int layerNumber;"),i.push("uniform vec3 coordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("in float vFlags;");for(var r=0;r> 16 & 0xF) == 1;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push("}")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz*coordinateScaler.xyz, layerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),i}(),Iu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null)}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new pu(this._scene,!1)),this._colorRenderer}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new fu(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new _u(this._scene)),this._depthRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new vu(this._scene)),this._pickMeshRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new gu(this._scene)),this._pickDepthRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new mu(this._scene)),this._occlusionRenderer}},{key:"shadowRenderer",get:function(){return this._shadowRenderer||(this._shadowRenderer=new yu(this._scene)),this._shadowRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new Pu(this._scene,!1)),this._snapInitRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new ku(this._scene)),this._snapRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy()}}]),e}(),Du={};var Su=new Uint8Array(4),Tu=new Float32Array(1),Lu=new Float32Array(3),Ru=new Float32Array(4),Uu=function(){function e(t){var i,r,s;x(this,e),console.info("VBOInstancingPointsLayer"),this.model=t.model,this.material=t.material,this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._renderers=(i=t.model.scene,r=i.id,(s=Du[r])||(s=new Iu(i),Du[r]=s,s._compile(),i.on("compile",(function(){s._compile()})),i.on("destroyed",(function(){delete Du[r],s._destroy()}))),s),this._aabb=$.collapseAABB3(),this._state=new qt({obb:$.OBB3(),numInstances:0,origin:t.origin?$.vec3(t.origin):null,geometry:t.geometry,positionsDecodeMatrix:t.geometry.positionsDecodeMatrix,colorsBuf:null,flagsBuf:null,offsetsBuf:null,modelMatrixCol0Buf:null,modelMatrixCol1Buf:null,modelMatrixCol2Buf:null,pickColorsBuf:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.geometry.numIndices,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],this._meshes=[],this._aabb=$.collapseAABB3(),this.aabbDirty=!0,this._finalized=!1}return C(e,[{key:"aabb",get:function(){if(this.aabbDirty){$.collapseAABB3(this._aabb);for(var e=0,t=this._meshes.length;e0){i.flagsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(t),t,1,e.DYNAMIC_DRAW,!1)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){i.offsetsBuf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,!1),this._offsets=[]}if(r.positionsCompressed&&r.positionsCompressed.length>0){i.positionsBuf=new Dt(e,e.ARRAY_BUFFER,r.positionsCompressed,r.positionsCompressed.length,3,e.STATIC_DRAW,!1),i.positionsDecodeMatrix=$.mat4(r.positionsDecodeMatrix)}if(r.colorsCompressed&&r.colorsCompressed.length>0){var s=new Uint8Array(r.colorsCompressed);i.colorsBuf=new Dt(e,e.ARRAY_BUFFER,s,s.length,4,e.STATIC_DRAW,!1)}if(this._modelMatrixCol0.length>0){var n=!1;i.modelMatrixCol0Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,n),i.modelMatrixCol1Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,n),i.modelMatrixCol2Buf=new Dt(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,n),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){i.pickColorsBuf=new Dt(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,!1),this._pickColors=[]}i.geometry=null,this._finalized=!0}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i)}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags(e,t)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){if(!this._finalized)throw"Not finalized";Su[0]=t[0],Su[1]=t[1],Su[2]=t[2],this._state.colorsBuf.setData(Su,3*e)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){if(!this._finalized)throw"Not finalized";var r=!!(t&Qe),s=!!(t&ze),n=!!(t&We),o=!!(t&Ke),a=!!(t&Xe),l=!!(t&He),u=!!(t&Ve),A=0;A|=!r||u||s||n&&!this.model.scene.highlightMaterial.glowThrough||o&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,A|=(!r||u?ao.NOT_RENDERED:o?ao.SILHOUETTE_SELECTED:n?ao.SILHOUETTE_HIGHLIGHTED:s?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED)<<4,A|=(!r||u?ao.NOT_RENDERED:o?ao.EDGES_SELECTED:n?ao.EDGES_HIGHLIGHTED:s?ao.EDGES_XRAYED:a?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED)<<8,A|=(r&&!u&&l?ao.PICK:ao.NOT_RENDERED)<<12,A|=(t&je?255:0)<<16,Tu[0]=A,this._state.flagsBuf.setData(Tu,e)}},{key:"setOffset",value:function(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(Lu[0]=t[0],Lu[1]=t[1],Lu[2]=t[2],this._state.offsetsBuf.setData(Lu,3*e)):this.model.error("Entity#offset not enabled for this Viewer")}},{key:"setMatrix",value:function(e,t){if(!this._finalized)throw"Not finalized";var i=4*e;Ru[0]=t[0],Ru[1]=t[4],Ru[2]=t[8],Ru[3]=t[12],this._state.modelMatrixCol0Buf.setData(Ru,i),Ru[0]=t[1],Ru[1]=t[5],Ru[2]=t[9],Ru[3]=t[13],this._state.modelMatrixCol1Buf.setData(Ru,i),Ru[0]=t[2],Ru[1]=t[6],Ru[2]=t[10],Ru[3]=t[14],this._state.modelMatrixCol2Buf.setData(Ru,i)}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED)}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED)}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED)}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawShadow",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawPickDepths",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawPickNormals",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK)}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK)}},{key:"destroy",value:function(){var e=this._state;e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}]),e}(),Ou=$.vec3(),Nu=$.vec3(),Qu=$.mat4(),Vu=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,s=r.camera,n=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=s.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uPerObjectDecodeMatrix,this._uPerVertexPosition,this.uPerObjectColorAndFlags,this._uPerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=Ou;if(f){var m=$.transformPoint3(c,u,Nu);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,Qu)}else p=d;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,8),o.drawArrays(o.LINES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,16),o.drawArrays(o.LINES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindLineIndicesTextures(this._program,this._uPerLineObject,this._uPerLineIndices,32),o.drawArrays(o.LINES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// LinesDataTextureColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uPerObjectDecodeMatrix;"),i.push("uniform highp sampler2D uPerObjectMatrix;"),i.push("uniform lowp usampler2D uPerObjectColorAndFlags;"),i.push("uniform mediump usampler2D uPerVertexPosition;"),i.push("uniform highp usampler2D uPerLineIndices;"),i.push("uniform mediump usampler2D uPerLineObject;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push(" int lineIndex = gl_VertexID / 2;"),i.push(" int h_packed_object_id_index = (lineIndex >> 3) & 4095;"),i.push(" int v_packed_object_id_index = (lineIndex >> 3) >> 12;"),i.push(" int objectIndex = int(texelFetch(uPerLineObject, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push(" ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" } else {"),i.push(" ivec4 packedVertexBase = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push(" ivec4 packedLineIndexBaseOffset = ivec4(texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push(" int lineIndexBaseOffset = (packedLineIndexBaseOffset.r << 24) + (packedLineIndexBaseOffset.g << 16) + (packedLineIndexBaseOffset.b << 8) + packedLineIndexBaseOffset.a;"),i.push(" int h_index = (lineIndex - lineIndexBaseOffset) & 4095;"),i.push(" int v_index = (lineIndex - lineIndexBaseOffset) >> 12;"),i.push(" ivec3 vertexIndices = ivec3(texelFetch(uPerLineIndices, ivec2(h_index, v_index), 0));"),i.push(" ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push(" int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push(" int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push(" mat4 objectInstanceMatrix = mat4 (texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uPerObjectDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push(" uvec4 flags = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push(" uvec4 flags2 = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push(" vec3 position = vec3(texelFetch(uPerVertexPosition, ivec2(indexPositionH, indexPositionV), 0));"),i.push(" uvec4 color = texelFetch (uPerObjectColorAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push(" if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push(" };"),i.push(" vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push(" vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push(" vFragDepth = 1.0 + clipPos.w;"),i.push(" isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push(" gl_Position = clipPos;"),i.push(" vec4 rgb = vec4(color.rgba);"),i.push(" vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState,i=t.getNumAllocatedSectionPlanes()>0,r=[];if(r.push("#version 300 es"),r.push("// LinesDataTextureColorRenderer 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;")),i){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),Hu=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null)}},{key:"eagerCreateRenders",value:function(){}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new Vu(this._scene,!1)),this._colorRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy()}}]),e}(),ju={};var Gu=C((function e(){x(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perLineNumberPortionId8Bits=[],this.perLineNumberPortionId16Bits=[],this.perLineNumberPortionId32Bits=[]})),zu=function(){function e(){x(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerLineIdPortionIds8Bits=null,this.texturePerLineIdPortionIds16Bits=null,this.texturePerLineIdPortionIds32Bits=null,this.texturePerLineIdIndices8Bits=null,this.texturePerLineIdIndices16Bits=null,this.texturePerLineIdIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerLineIdIndices8Bits,16:this.texturePerLineIdIndices16Bits,32:this.texturePerLineIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerLineIdPortionIds8Bits,16:this.texturePerLineIdPortionIds16Bits,32:this.texturePerLineIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,r,s){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,r,3),this.texturePerObjectInstanceMatrices.bindTexture(e,s,4)}},{key:"bindLineIndicesTextures",value:function(e,t,i,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.indicesPerBitnessTextures[r].bindTexture(e,i,6)}}]),e}(),Wu=function(){function e(t,i,r,s){var n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;x(this,e),this._gl=t,this._texture=i,this._textureWidth=r,this._textureHeight=s,this._textureData=n}return C(e,[{key:"bindTexture",value:function(e,t,i){return e.bindTexture(t,this,i)}},{key:"bind",value:function(e){return this._gl.activeTexture(this._gl["TEXTURE"+e]),this._gl.bindTexture(this._gl.TEXTURE_2D,this._texture),!0}},{key:"unbind",value:function(e){}}]),e}(),Ku={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalLines:0,totalLines8Bits:0,totalLines16Bits:0,totalLines32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(Ku,null,4));var e=0;Object.keys(Ku).forEach((function(t){t.startsWith("size")&&(e+=Ku[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/Ku.totalLines).toFixed(2)));var t={};Object.keys(Ku).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((Ku[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var Xu=function(){function e(){x(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"generateTextureForColorsAndFlags",value:function(e,t,i,r,s){var n=t.length;this.numPortions=n;var o=4096,a=Math.ceil(n/512);if(0===a)throw"texture height===0";var l=new Uint8Array(16384*a);Ku.sizeDataColorsAndFlags+=l.byteLength,Ku.numberOfTextures++;for(var u=0;u>24&255,r[u]>>16&255,r[u]>>8&255,255&r[u]],32*u+16),l.set([s[u]>>24&255,s[u]>>16&255,s[u]>>8&255,255&s[u]],32*u+20);var A=e.createTexture();return e.bindTexture(e.TEXTURE_2D,A),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,o,a),e.texSubImage2D(e.TEXTURE_2D,0,0,0,o,a,e.RGBA_INTEGER,e.UNSIGNED_BYTE,l,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,A,o,a,l)}},{key:"generateTextureForObjectOffsets",value:function(e,t){var i=512,r=Math.ceil(t/i);if(0===r)throw"texture height===0";var s=new Float32Array(1536*r).fill(0);Ku.sizeDataTextureOffsets+=s.byteLength,Ku.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,r,e.RGB,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,n,i,r,s)}},{key:"generateTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var r=2048,s=Math.ceil(i/512),n=new Float32Array(8192*s);Ku.numberOfTextures++;for(var o=0;o65536&&Ku.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var s=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/2})),(this._state.numVertices+n>4096*Ju||s+o>4096*Ju)&&Ku.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*Ju&&s+o<=4096*Ju)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var r=[];t.buckets.forEach((function(e,s){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(s):"".concat(t.id,"#").concat(s),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);r.push(a)}));var s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(r),this.model.numPortions++,this._meshes.push(e),s}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/2/8)*2;Ku.overheadSizeAlignementIndices+=2*(i-t.indices.length);var r=new Uint32Array(i);r.fill(0),r.set(t.indices),t.indices=r}var s=t.positionsCompressed,n=t.indices,o=this._buffer;o.positionsCompressed.push(s);var a,l=o.lenPositionsCompressed/3,u=s.length/3;o.lenPositionsCompressed+=s.length;var A,c=0;n&&(c=n.length/2,u<=256?(A=o.indices8Bits,a=o.lenIndices8Bits/2,o.lenIndices8Bits+=n.length):u<=65536?(A=o.indices16Bits,a=o.lenIndices16Bits/2,o.lenIndices16Bits+=n.length):(A=o.indices32Bits,a=o.lenIndices32Bits/2,o.lenIndices32Bits+=n.length),A.push(n));return this._state.numVertices+=u,Ku.numberOfGeometries++,{vertexBase:l,numVertices:u,numLines:c,indicesBase:a}}},{key:"_createSubPortion",value:function(e,t){var i,r=e.color,s=e.colors,n=e.opacity,o=e.meshMatrix,a=e.pickColor,l=this._buffer,u=this._state;l.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),l.perObjectInstancePositioningMatrices.push(o||tA),l.perObjectSolid.push(!!e.solid),s?l.perObjectColors.push([255*s[0],255*s[1],255*s[2],255]):r&&l.perObjectColors.push([r[0],r[1],r[2],n]),l.perObjectPickColors.push(a),l.perObjectVertexBases.push(t.vertexBase),i=t.numVertices<=256?u.numIndices8Bits:t.numVertices<=65536?u.numIndices16Bits:u.numIndices32Bits,l.perObjectIndexBaseOffsets.push(i/2-t.indicesBase);var A=this._subPortions.length;if(t.numLines>0){var c,h=2*t.numLines;t.numVertices<=256?(c=l.perLineNumberPortionId8Bits,u.numIndices8Bits+=h,Ku.totalLines8Bits+=t.numLines):t.numVertices<=65536?(c=l.perLineNumberPortionId16Bits,u.numIndices16Bits+=h,Ku.totalLines16Bits+=t.numLines):(c=l.perLineNumberPortionId32Bits,u.numIndices32Bits+=h,Ku.totalLines32Bits+=t.numLines),Ku.totalLines+=t.numLines;for(var d=0;d0&&(i.texturePerLineIdIndices8Bits=this._dataTextureGenerator.generateTextureFor8BitIndices(r,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(i.texturePerLineIdIndices16Bits=this._dataTextureGenerator.generateTextureFor16BitIndices(r,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(i.texturePerLineIdIndices32Bits=this._dataTextureGenerator.generateTextureFor32BitIndices(r,s.indices32Bits,s.lenIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dataTextureState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,qu))}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=this._portionToSubPortionsMap[e],n=0,o=s.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var s,n,o=!!(t&Qe),a=!!(t&ze),l=!!(t&We),u=!!(t&Ke),A=!!(t&He),c=!!(t&Ve);s=!o||c||a?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!o||c?ao.NOT_RENDERED:u?ao.SILHOUETTE_SELECTED:l?ao.SILHOUETTE_HIGHLIGHTED:a?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var h=o&&!c&&A?ao.PICK:ao.NOT_RENDERED,d=this._dataTextureState,p=this.model.scene.canvas.gl;qu[0]=s,qu[1]=n,qu[3]=h,d.texturePerObjectColorsAndFlags._textureData.set(qu,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),p.bindTexture(p.TEXTURE_2D,d.texturePerObjectColorsAndFlags._texture),p.texSubImage2D(p.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,p.RGBA_INTEGER,p.UNSIGNED_BYTE,qu))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],s=0,n=r.length;s2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&je?255:0,s=this._dataTextureState,n=this.model.scene.canvas.gl;qu[0]=r,qu[1]=0,qu[2]=1,qu[3]=2,s.texturePerObjectColorsAndFlags._textureData.set(qu,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,qu))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,$u))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,r.RGBA,r.FLOAT,Zu))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE)}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT)}},{key:"drawDepth",value:function(e,t){}},{key:"drawNormals",value:function(e,t){}},{key:"drawSilhouetteXRayed",value:function(e,t){}},{key:"drawSilhouetteHighlighted",value:function(e,t){}},{key:"drawSilhouetteSelected",value:function(e,t){}},{key:"drawEdgesColorOpaque",value:function(e,t){}},{key:"drawEdgesColorTransparent",value:function(e,t){}},{key:"drawEdgesHighlighted",value:function(e,t){}},{key:"drawEdgesSelected",value:function(e,t){}},{key:"drawEdgesXRayed",value:function(e,t){}},{key:"drawOcclusion",value:function(e,t){}},{key:"drawShadow",value:function(e,t){}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){}},{key:"drawPickDepths",value:function(e,t){}},{key:"drawSnapInit",value:function(e,t){}},{key:"drawSnap",value:function(e,t){}},{key:"drawPickNormals",value:function(e,t){}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),rA=$.vec3(),sA=$.vec3(),nA=$.vec3();$.vec3();var oA=$.vec4(),aA=$.mat4(),lA=function(){function e(t,i){x(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,s=r.camera,n=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=rA;if(f){var m=$.transformPoint3(c,u,sA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(s.viewMatrix,g,aA),(p=nA)[0]=s.eye[0]-g[0],p[1]=s.eye[1]-g[1],p[2]=s.eye[2]-g[2]}else d=s.viewMatrix,p=s.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new It(t,this._buildShader()),this._program.errors)return this.errors=this._program.errors,void console.error(this.errors);var r=this._program;this._uRenderPass=r.getLocation("renderPass"),this._uLightAmbient=r.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(var s=i.lights,n=0,o=s.length;n0,n=[];n.push("#version 300 es"),n.push("// TrianglesDataTextureColorRenderer vertex shader"),n.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),n.push("precision highp float;"),n.push("precision highp int;"),n.push("precision highp usampler2D;"),n.push("precision highp isampler2D;"),n.push("precision highp sampler2D;"),n.push("#else"),n.push("precision mediump float;"),n.push("precision mediump int;"),n.push("precision mediump usampler2D;"),n.push("precision mediump isampler2D;"),n.push("precision mediump sampler2D;"),n.push("#endif"),n.push("uniform int renderPass;"),n.push("uniform mat4 sceneModelMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),n.push("uniform highp sampler2D uTexturePerObjectMatrix;"),n.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),n.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),n.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),n.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),n.push("uniform vec3 uCameraEyeRtc;"),n.push("vec3 positions[3];"),t.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),n.push("out float vFragDepth;"),n.push("out float isPerspective;")),n.push("bool isPerspectiveMatrix(mat4 m) {"),n.push(" return (m[2][3] == - 1.0);"),n.push("}"),n.push("uniform vec4 lightAmbient;");for(var o=0,a=r.lights.length;o> 3) & 4095;"),n.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),n.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),n.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),n.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),n.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),n.push("if (int(flags.x) != renderPass) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("} else {"),n.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),n.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),n.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),n.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),n.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),n.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),n.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),n.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),n.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),n.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),n.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),n.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),n.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),n.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),n.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),n.push("if (color.a == 0u) {"),n.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),n.push(" return;"),n.push("};"),n.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),n.push("vec3 position;"),n.push("position = positions[gl_VertexID % 3];"),n.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),n.push("if (solid != 1u) {"),n.push("if (isPerspectiveMatrix(projMatrix)) {"),n.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),n.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("} else {"),n.push("if (viewNormal.z < 0.0) {"),n.push("position = positions[2 - (gl_VertexID % 3)];"),n.push("viewNormal = -viewNormal;"),n.push("}"),n.push("}"),n.push("}"),n.push("vec4 worldPosition = sceneModelMatrix * ((objectDecodeAndInstanceMatrix * vec4(position, 1.0))); "),n.push("vec4 viewPosition = viewMatrix * worldPosition; "),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;");for(var l=0,u=r.lights.length;l0,r=[];if(r.push("#version 300 es"),r.push("// TrianglesDataTextureColorRenderer fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),e.logarithmicDepthBufferEnabled&&(r.push("in float isPerspective;"),r.push("uniform float logDepthBufFC;"),r.push("in float vFragDepth;")),this._withSAO&&(r.push("uniform sampler2D uOcclusionTexture;"),r.push("uniform vec4 uSAOParams;"),r.push("const float packUpscale = 256. / 255.;"),r.push("const float unpackDownScale = 255. / 256.;"),r.push("const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );"),r.push("const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),r.push("float unpackRGBToFloat( const in vec4 v ) {"),r.push(" return dot( v, unPackFactors );"),r.push("}")),i){r.push("in vec4 vWorldPosition;"),r.push("flat in uint vFlags2;");for(var s=0,n=t.getNumAllocatedSectionPlanes();s 0u;"),r.push(" if (clippable) {"),r.push(" float dist = 0.0;");for(var o=0,a=t.getNumAllocatedSectionPlanes();o 0.0) { "),r.push(" discard;"),r.push(" }"),r.push("}")}return e.logarithmicDepthBufferEnabled&&r.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),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(vColor.rgb * ambient, 1.0);")):r.push(" outColor = vColor;"),r.push("}"),r}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),uA=new Float32Array([1,1,1]),AA=$.vec3(),cA=$.vec3(),hA=$.vec3();$.vec3();var dA=$.mat4(),pA=function(){function e(t,i){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,s=r.camera,n=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate,d=s.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=AA;if(u){var g=cA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Le(d,v,dA),(f=hA)[0]=s.eye[0]-v[0],f[1]=s.eye[1]-v[1],f[2]=s.eye[2]-v[2]}else p=d,f=s.eye;if(o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),i===ao.SILHOUETTE_XRAYED){var m=r.xrayMaterial._state,_=m.fillColor,y=m.fillAlpha;o.uniform4f(this._uColor,_[0],_[1],_[2],y)}else if(i===ao.SILHOUETTE_HIGHLIGHTED){var b=r.highlightMaterial._state,w=b.fillColor,B=b.fillAlpha;o.uniform4f(this._uColor,w[0],w[1],w[2],B)}else if(i===ao.SILHOUETTE_SELECTED){var x=r.selectedMaterial._state,P=x.fillColor,C=x.fillAlpha;o.uniform4f(this._uColor,P[0],P[1],P[2],C)}else o.uniform4fv(this._uColor,uA);if(r.logarithmicDepthBufferEnabled){var M=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,M)}var E=r._sectionPlanesState.getNumAllocatedSectionPlanes(),F=r._sectionPlanesState.sectionPlanes.length;if(E>0)for(var k=r._sectionPlanesState.sectionPlanes,I=t.layerIndex*F,D=n.renderFlags,S=0;S0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture silhouette vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.y) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = color;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),fA=new Float32Array([0,0,0,1]),vA=$.vec3(),gA=$.vec3();$.vec3();var mA=$.mat4(),_A=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=r.position,c=r.rotationMatrix,h=r.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=vA;if(f){var m=$.transformPoint3(c,u,gA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,mA)}else p=d;if(o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),i===ao.EDGES_XRAYED){var _=s.xrayMaterial._state,y=_.edgeColor,b=_.edgeAlpha;o.uniform4f(this._uColor,y[0],y[1],y[2],b)}else if(i===ao.EDGES_HIGHLIGHTED){var w=s.highlightMaterial._state,B=w.edgeColor,x=w.edgeAlpha;o.uniform4f(this._uColor,B[0],B[1],B[2],x)}else if(i===ao.EDGES_SELECTED){var P=s.selectedMaterial._state,C=P.edgeColor,M=P.edgeAlpha;o.uniform4f(this._uColor,C[0],C[1],C[2],M)}else o.uniform4fv(this._uColor,fA);var E=s._sectionPlanesState.getNumAllocatedSectionPlanes(),F=s._sectionPlanesState.sectionPlanes.length;if(E>0)for(var k=s._sectionPlanesState.sectionPlanes,I=t.layerIndex*F,D=r.renderFlags,S=0;S0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("mat4 matrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesEdgesRenderer fragment shader"),e.logarithmicDepthBufferEnabled&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),yA=$.vec3(),bA=$.vec3(),wA=$.mat4(),BA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=r.position,c=r.rotationMatrix,h=r.rotationMatrixConjugate,d=n.viewMatrix;if(this._program||(this._allocate(),!this.errors)){var p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=yA;if(f){var m=$.transformPoint3(c,u,bA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],p=Le(d,g,wA)}else p=d;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),y=s._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=s._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=r.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),o.drawArrays(o.LINES,0,a.numEdgeIndices8Bits)),a.numEdgeIndices16Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),o.drawArrays(o.LINES,0,a.numEdgeIndices16Bits)),a.numEdgeIndices32Bits>0&&(l.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),o.drawArrays(o.LINES,0,a.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled,i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uObjectPerObjectOffsets;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;")),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vColor;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.z) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push("vec4 rgb = vec4(color.rgba);"),i.push("vColor = vec4(float(rgb.r*0.5) / 255.0, float(rgb.g*0.5) / 255.0, float(rgb.b*0.5) / 255.0, float(rgb.a) / 255.0);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureEdgesColorRenderer"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { discard; }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outColor = vColor;"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),xA=$.vec3(),PA=$.vec3(),CA=$.vec3(),MA=$.mat4(),EA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(t),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e));var r,s,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate;A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==c[0]||0!==c[1]||0!==c[2],v=0!==h[0]||0!==h[1]||0!==h[2];if(f||v){var g=xA;if(f){var m=$.transformPoint3(d,c,PA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=h[0],g[1]+=h[1],g[2]+=h[2],r=Le(a.viewMatrix,g,MA),(s=CA)[0]=a.eye[0]-g[0],s[1]=a.eye[1]-g[1],s[2]=a.eye[2]-g[2]}else r=a.viewMatrix,s=a.eye;if(l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),l.uniform3fv(this._uCameraEyeRtc,s),l.uniform1i(this._uRenderPass,i),o.logarithmicDepthBufferEnabled){var _=2/(Math.log(a.project.far+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,_)}var y=o._sectionPlanesState.getNumAllocatedSectionPlanes(),b=o._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=o._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry picking vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("smooth out vec4 vWorldPosition;"),i.push("flat out uvec4 vFlags2;")),i.push("out vec4 vPickColor;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0)) / 255.0;"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry picking fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uvec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" outPickColor = vPickColor; "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),FA=$.vec3(),kA=$.vec3(),IA=$.vec3();$.vec3();var DA=$.mat4(),SA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r,s,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=e.pickViewMatrix||a.viewMatrix;if(this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),c||0!==h[0]||0!==h[1]||0!==h[2]){var v=FA;if(c){var g=kA;$.transformPoint3(d,c,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=h[0],v[1]+=h[1],v[2]+=h[2],r=Le(f,v,DA),(s=IA)[0]=a.eye[0]-v[0],s[1]=a.eye[1]-v[1],s[2]=a.eye[2]-v[2],e.snapPickOrigin[0]=v[0],e.snapPickOrigin[1]=v[1],e.snapPickOrigin[2]=v[2]}else r=f,s=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;if(l.uniform3fv(this._uCameraEyeRtc,s),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniform2fv(this._uPickClipPos,e.pickClipPos),l.uniform2f(this._uDrawingBufferSize,l.drawingBufferWidth,l.drawingBufferHeight),l.uniform1f(this._uPickZNear,e.pickZNear),l.uniform1f(this._uPickZFar,e.pickZFar),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix),o.logarithmicDepthBufferEnabled){var m=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,m)}var _=o._sectionPlanesState.getNumAllocatedSectionPlanes(),y=o._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=o._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=n.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform bool pickInvisible;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = remapClipPos(clipPos);"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("uniform float pickZNear;"),i.push("uniform float pickZFar;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(r=0;r 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),i.push(" outPackedDepth = packDepth(zNormalizedDepth); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),TA=$.vec3(),LA=$.vec3(),RA=$.vec3(),UA=$.vec3();$.vec3();var OA=$.mat4(),NA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){if(this._program||(this._allocate(),!this.errors)){e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r,s,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=TA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=LA;if(m){var b=$.transformPoint3(d,c,RA);y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],r=Le(v,y,OA),(s=UA)[0]=a.eye[0]-y[0],s[1]=a.eye[1]-y[1],s[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else r=v,s=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,s),l.uniform2fv(this.uVectorA,e.snapVectorA),l.uniform2fv(this.uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var w=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,w);var B=o._sectionPlanesState.getNumAllocatedSectionPlanes(),x=o._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=n.renderFlags,E=0;E0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,8),l.drawArrays(S,0,u.numEdgeIndices8Bits)),u.numEdgeIndices16Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,16),l.drawArrays(S,0,u.numEdgeIndices16Bits)),u.numEdgeIndices32Bits>0&&(A.bindEdgeIndicesTextures(this._program,this._uTexturePerEdgeIdPortionIds,this._uTexturePerPolygonIdEdgeIndices,32),l.drawArrays(S,0,u.numEdgeIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// Batched geometry edges drawing vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdEdgeIndices;"),i.push("uniform mediump usampler2D uTexturePerEdgeIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uSnapVectorA;"),i.push("uniform vec2 uSnapInvVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out float isPerspective;"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uSnapVectorA.x) * uSnapInvVectorAB.x;"),i.push(" float y = (clipPos.y - uSnapVectorA.y) * uSnapInvVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("out vec4 vViewPosition;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int edgeIndex = gl_VertexID / 2;"),i.push("int h_packed_object_id_index = (edgeIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (edgeIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerEdgeIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedEdgeIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+6, objectIndexCoords.y), 0));"),i.push("int edgeIndexBaseOffset = (packedEdgeIndexBaseOffset.r << 24) + (packedEdgeIndexBaseOffset.g << 16) + (packedEdgeIndexBaseOffset.b << 8) + packedEdgeIndexBaseOffset.a;"),i.push("int h_index = (edgeIndex - edgeIndexBaseOffset) & 4095;"),i.push("int v_index = (edgeIndex - edgeIndexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdEdgeIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),i.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("vec3 position = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH, indexPositionV), 0));"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2.r;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vViewPosition = clipPos;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push("gl_PointSize = 1.0;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture pick depth fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, uLayerNumber);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),QA=$.vec3(),VA=$.vec3(),HA=$.vec3(),jA=$.vec3();$.vec3();var GA=$.mat4(),zA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());var r,s,n=t.model,o=n.scene,a=o.camera,l=o.canvas.gl,u=t._state,A=u.textureState,c=t._state.origin,h=n.position,d=n.rotationMatrix,p=n.rotationMatrixConjugate,f=t.aabb,v=e.pickViewMatrix||a.viewMatrix,g=QA;g[0]=$.safeInv(f[3]-f[0])*$.MAX_INT,g[1]=$.safeInv(f[4]-f[1])*$.MAX_INT,g[2]=$.safeInv(f[5]-f[2])*$.MAX_INT,e.snapPickCoordinateScale[0]=$.safeInv(g[0]),e.snapPickCoordinateScale[1]=$.safeInv(g[1]),e.snapPickCoordinateScale[2]=$.safeInv(g[2]),A.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var m=0!==c[0]||0!==c[1]||0!==c[2],_=0!==h[0]||0!==h[1]||0!==h[2];if(m||_){var y=VA;if(m){var b=HA;$.transformPoint3(d,c,b),y[0]=b[0],y[1]=b[1],y[2]=b[2]}else y[0]=0,y[1]=0,y[2]=0;y[0]+=h[0],y[1]+=h[1],y[2]+=h[2],r=Le(v,y,GA),(s=jA)[0]=a.eye[0]-y[0],s[1]=a.eye[1]-y[1],s[2]=a.eye[2]-y[2],e.snapPickOrigin[0]=y[0],e.snapPickOrigin[1]=y[1],e.snapPickOrigin[2]=y[2]}else r=v,s=a.eye,e.snapPickOrigin[0]=0,e.snapPickOrigin[1]=0,e.snapPickOrigin[2]=0;l.uniform3fv(this._uCameraEyeRtc,s),l.uniform2fv(this._uVectorA,e.snapVectorA),l.uniform2fv(this._uInverseVectorAB,e.snapInvVectorAB),l.uniform1i(this._uLayerNumber,e.snapPickLayerNumber),l.uniform3fv(this._uCoordinateScaler,g),l.uniform1i(this._uRenderPass,i),l.uniform1i(this._uPickInvisible,e.pickInvisible),l.uniformMatrix4fv(this._uSceneWorldModelMatrix,!1,p),l.uniformMatrix4fv(this._uViewMatrix,!1,r),l.uniformMatrix4fv(this._uProjMatrix,!1,a.projMatrix);var w=2/(Math.log(e.pickZFar+1)/Math.LN2);l.uniform1f(this._uLogDepthBufFC,w);var B=o._sectionPlanesState.getNumAllocatedSectionPlanes(),x=o._sectionPlanesState.sectionPlanes.length;if(B>0)for(var P=o._sectionPlanesState.sectionPlanes,C=t.layerIndex*x,M=n.renderFlags,E=0;E0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),l.drawArrays(l.TRIANGLES,0,u.numIndices8Bits)),u.numIndices16Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),l.drawArrays(l.TRIANGLES,0,u.numIndices16Bits)),u.numIndices32Bits>0&&(A.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),l.drawArrays(l.TRIANGLES,0,u.numIndices32Bits)),e.drawElements++}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uSceneWorldModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("uniform vec2 uVectorAB;"),i.push("uniform vec2 uInverseVectorAB;"),i.push("vec3 positions[3];"),i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("vec2 remapClipPos(vec2 clipPos) {"),i.push(" float x = (clipPos.x - uVectorAB.x) * uInverseVectorAB.x;"),i.push(" float y = (clipPos.y - uVectorAB.y) * uInverseVectorAB.y;"),i.push(" return vec2(x, y);"),i.push("}"),i.push("flat out vec4 vPickColor;"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("out highp vec3 relativeToOriginPosition;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("{"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" } else {"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" viewNormal = -viewNormal;"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("relativeToOriginPosition = worldPosition.xyz;"),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("vPickColor = vec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+1, objectIndexCoords.y), 0));"),i.push("vec4 clipPos = projMatrix * viewPosition;"),i.push("float tmp = clipPos.w;"),i.push("clipPos.xyzw /= tmp;"),i.push("clipPos.xy = remapClipPos(clipPos.xy);"),i.push("clipPos.xyzw *= tmp;"),i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));"),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// DTXTrianglesSnapInitRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;"),i.push("uniform int uLayerNumber;"),i.push("uniform vec3 uCoordinateScaler;"),i.push("in vec4 vWorldPosition;"),i.push("flat in vec4 vPickColor;"),t){i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0;n 0.0) { discard; }"),i.push(" }")}return i.push(" float dx = dFdx(vFragDepth);"),i.push(" float dy = dFdy(vFragDepth);"),i.push(" float diff = sqrt(dx*dx+dy*dy);"),i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth + diff ) * logDepthBufFC * 0.5;"),i.push("outCoords = ivec4(relativeToOriginPosition.xyz * uCoordinateScaler.xyz, - uLayerNumber);"),i.push("vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push("vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push("vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push("outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("outPickColor = uvec4(vPickColor);"),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),WA=$.vec3(),KA=$.vec3(),XA=$.vec3();$.vec3();var YA=$.mat4(),JA=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=r.position,c=r.rotationMatrix,h=r.rotationMatrixConjugate,d=e.pickViewMatrix||n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var p,f;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix),u||0!==A[0]||0!==A[1]||0!==A[2]){var v=WA;if(u){var g=KA;$.transformPoint3(c,u,g),v[0]=g[0],v[1]=g[1],v[2]=g[2]}else v[0]=0,v[1]=0,v[2]=0;v[0]+=A[0],v[1]+=A[1],v[2]+=A[2],p=Le(d,v,YA),(f=XA)[0]=n.eye[0]-v[0],f[1]=n.eye[1]-v[1],f[2]=n.eye[2]-v[2]}else p=d,f=n.eye;o.uniform3fv(this._uCameraEyeRtc,f),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,p),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix);var m=s._sectionPlanesState.getNumAllocatedSectionPlanes(),_=s._sectionPlanesState.sectionPlanes.length;if(m>0)for(var y=s._sectionPlanesState.sectionPlanes,b=t.layerIndex*_,w=r.renderFlags,B=0;B0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uWorldMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// TrianglesDataTextureOcclusionRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("if (solid != 1u) {"),i.push(" if (isPerspectiveMatrix(projMatrix)) {"),i.push(" vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" } else {"),i.push(" vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push(" if (viewNormal.z < 0.0) {"),i.push(" position = positions[2 - (gl_VertexID % 3)];"),i.push(" }"),i.push(" }"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene._sectionPlanesState,t=e.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTextureColorRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return i.push(" outColor = vec4(0.0, 0.0, 1.0, 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ZA=$.vec3(),qA=$.vec3(),$A=$.vec3();$.vec3();var ec=$.mat4(),tc=function(){function e(t){x(this,e),this._scene=t,this._allocate(),this._hash=this._getHash()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,s=r.camera,n=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=ZA;if(f){var m=$.transformPoint3(c,u,qA);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(s.viewMatrix,g,ec),(p=$A)[0]=s.eye[0]-g[0],p[1]=s.eye[1]-g[1],p[2]=s.eye[2]-g[2]}else d=s.viewMatrix,p=s.eye;if(o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("objectDecodeAndInstanceMatrix"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// Triangles dataTexture draw vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out highp vec2 vHighPrecisionZW;"),t&&(i.push("out vec4 vWorldPosition;"),i.push("flat out uint vFlags2;")),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2.r;")),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Triangles dataTexture draw fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),i.push("in highp vec2 vHighPrecisionZW;"),i.push("out vec4 outColor;"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),i.push(" outColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ic=$.vec3(),rc=$.vec3(),sc=$.vec3();$.vec3();var nc=$.mat4(),oc=function(){function e(t){x(this,e),this._scene=t,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){return this._scene._sectionPlanesState.getHash()}},{key:"drawLayer",value:function(e,t,i){var r=t.model,s=r.scene,n=s.camera,o=s.canvas.gl,a=t._state,l=t._state.origin,u=r.position,A=r.rotationMatrix,c=r.rotationMatrixConjugate,h=n.viewMatrix;if(this._program||(this._allocate(t),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t));var f=0!==l[0]||0!==l[1]||0!==l[2],v=0!==u[0]||0!==u[1]||0!==u[2];if(f||v){var g=ic;if(f){var m=rc;$.transformPoint3(A,l,m),g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=u[0],g[1]+=u[1],g[2]+=u[2],d=Le(h,g,nc),(p=sc)[0]=n.eye[0]-g[0],p[1]=n.eye[1]-g[1],p[2]=n.eye[2]-g[2]}else d=h,p=n.eye;o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uWorldMatrix,!1,c),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,n.projMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,n.viewNormalMatrix),o.uniformMatrix4fv(this._uWorldNormalMatrix,!1,r.worldNormalMatrix);var _=s._sectionPlanesState.getNumAllocatedSectionPlanes(),y=s._sectionPlanesState.sectionPlanes.length;if(_>0)for(var b=s._sectionPlanesState.sectionPlanes,w=t.layerIndex*y,B=r.renderFlags,x=0;x<_;x++){var P=this._uSectionPlanes[x];if(P)if(x0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 objectDecodeAndInstanceMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("out float vFragDepth;"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("varying float isPerspective;")),i.push("vec3 octDecode(vec2 oct) {"),i.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push(" if (v.z < 0.0) {"),i.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push(" }"),i.push(" return normalize(v);"),i.push("}"),t&&(i.push("out vec4 vWorldPosition;"),i.push("out vec4 vFlags2;")),i.push("out vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push(" gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push(" } else {"),i.push(" vec4 worldPosition = worldMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push(" worldPosition.xyz = worldPosition.xyz + offset;"),i.push(" vec4 viewPosition = viewMatrix * worldPosition; "),i.push(" vec4 worldNormal = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push(" vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push(" vWorldPosition = worldPosition;"),i.push(" vFlags2 = flags2;")),i.push(" vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(bt.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;")),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("gl_Position = clipPos;"),i.push(" }"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),t){i.push("in vec4 vWorldPosition;"),i.push("in vec4 vFlags2;");for(var r=0;r 0.0);"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var s=0;s 0.0) { discard; }"),i.push(" }")}return e.logarithmicDepthBufferEnabled&&bt.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push(" gl_FragDepthEXT = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),ac=$.vec3(),lc=$.vec3(),uc=$.vec3();$.vec3(),$.vec4();var Ac=$.mat4(),cc=function(){function e(t,i){x(this,e),this._scene=t,this._withSAO=i,this._hash=this._getHash(),this._allocate()}return C(e,[{key:"getValid",value:function(){return this._hash===this._getHash()}},{key:"_getHash",value:function(){var e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}},{key:"drawLayer",value:function(e,t,i){var r=this._scene,s=r.camera,n=t.model,o=r.canvas.gl,a=t._state,l=a.textureState,u=t._state.origin,A=n.position,c=n.rotationMatrix,h=n.rotationMatrixConjugate;if(this._program||(this._allocate(),!this.errors)){var d,p;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,a)),l.bindCommonTextures(this._program,this.uTexturePerObjectPositionsDecodeMatrix,this._uTexturePerVertexIdCoordinates,this.uTexturePerObjectColorsAndFlags,this._uTexturePerObjectMatrix);var f=0!==u[0]||0!==u[1]||0!==u[2],v=0!==A[0]||0!==A[1]||0!==A[2];if(f||v){var g=ac;if(f){var m=$.transformPoint3(c,u,lc);g[0]=m[0],g[1]=m[1],g[2]=m[2]}else g[0]=0,g[1]=0,g[2]=0;g[0]+=A[0],g[1]+=A[1],g[2]+=A[2],d=Le(s.viewMatrix,g,Ac),(p=uc)[0]=s.eye[0]-g[0],p[1]=s.eye[1]-g[1],p[2]=s.eye[2]-g[2]}else d=s.viewMatrix,p=s.eye;if(o.uniform2fv(this._uPickClipPos,e.pickClipPos),o.uniform2f(this._uDrawingBufferSize,o.drawingBufferWidth,o.drawingBufferHeight),o.uniformMatrix4fv(this._uSceneModelMatrix,!1,h),o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uProjMatrix,!1,s.projMatrix),o.uniform3fv(this._uCameraEyeRtc,p),o.uniform1i(this._uRenderPass,i),r.logarithmicDepthBufferEnabled){var _=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,_)}var y=r._sectionPlanesState.getNumAllocatedSectionPlanes(),b=r._sectionPlanesState.sectionPlanes.length;if(y>0)for(var w=r._sectionPlanesState.sectionPlanes,B=t.layerIndex*b,x=n.renderFlags,P=0;P0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,8),o.drawArrays(o.TRIANGLES,0,a.numIndices8Bits)),a.numIndices16Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,16),o.drawArrays(o.TRIANGLES,0,a.numIndices16Bits)),a.numIndices32Bits>0&&(l.bindTriangleIndicesTextures(this._program,this._uTexturePerPolygonIdPortionIds,this._uTexturePerPolygonIdIndices,32),o.drawArrays(o.TRIANGLES,0,a.numIndices32Bits)),e.drawElements++}}},{key:"_allocate",value:function(){var e=this._scene,t=e.canvas.gl;if(this._program=new It(t,this._buildShader()),this._program.errors)this.errors=this._program.errors;else{var i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPickClipPos=i.getLocation("pickClipPos"),this._uDrawingBufferSize=i.getLocation("drawingBufferSize"),this._uSceneModelMatrix=i.getLocation("sceneModelMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r0,i=[];return i.push("#version 300 es"),i.push("// trianglesDatatextureNormalsRenderer vertex shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("precision highp usampler2D;"),i.push("precision highp isampler2D;"),i.push("precision highp sampler2D;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("precision mediump usampler2D;"),i.push("precision mediump isampler2D;"),i.push("precision mediump sampler2D;"),i.push("#endif"),i.push("uniform int renderPass;"),e.entityOffsetsEnabled&&i.push("in vec3 offset;"),i.push("uniform mat4 sceneModelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform highp sampler2D uObjectPerObjectPositionsDecodeMatrix;"),i.push("uniform lowp usampler2D uObjectPerObjectColorsAndFlags;"),i.push("uniform highp sampler2D uTexturePerObjectMatrix;"),i.push("uniform mediump usampler2D uTexturePerVertexIdCoordinates;"),i.push("uniform highp usampler2D uTexturePerPolygonIdIndices;"),i.push("uniform mediump usampler2D uTexturePerPolygonIdPortionIds;"),i.push("uniform vec3 uCameraEyeRtc;"),i.push("vec3 positions[3];"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),i.push("out float vFragDepth;"),i.push("out float isPerspective;")),i.push("uniform vec2 pickClipPos;"),i.push("uniform vec2 drawingBufferSize;"),i.push("vec4 remapClipPos(vec4 clipPos) {"),i.push(" clipPos.xy /= clipPos.w;"),i.push(" clipPos.xy = (clipPos.xy - pickClipPos) * drawingBufferSize;"),i.push(" clipPos.xy *= clipPos.w;"),i.push(" return clipPos;"),i.push("}"),i.push("bool isPerspectiveMatrix(mat4 m) {"),i.push(" return (m[2][3] == - 1.0);"),i.push("}"),i.push("out vec4 vWorldPosition;"),t&&i.push("flat out uint vFlags2;"),i.push("void main(void) {"),i.push("int polygonIndex = gl_VertexID / 3;"),i.push("int h_packed_object_id_index = (polygonIndex >> 3) & 4095;"),i.push("int v_packed_object_id_index = (polygonIndex >> 3) >> 12;"),i.push("int objectIndex = int(texelFetch(uTexturePerPolygonIdPortionIds, ivec2(h_packed_object_id_index, v_packed_object_id_index), 0).r);"),i.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),i.push("uvec4 flags = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+2, objectIndexCoords.y), 0);"),i.push("uvec4 flags2 = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+3, objectIndexCoords.y), 0);"),i.push("if (int(flags.w) != renderPass) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("} else {"),i.push("ivec4 packedVertexBase = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+4, objectIndexCoords.y), 0));"),i.push("ivec4 packedIndexBaseOffset = ivec4(texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+5, objectIndexCoords.y), 0));"),i.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),i.push("int h_index = (polygonIndex - indexBaseOffset) & 4095;"),i.push("int v_index = (polygonIndex - indexBaseOffset) >> 12;"),i.push("ivec3 vertexIndices = ivec3(texelFetch(uTexturePerPolygonIdIndices, ivec2(h_index, v_index), 0));"),i.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),i.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),i.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),i.push("mat4 objectInstanceMatrix = mat4 (texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uTexturePerObjectMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4 (texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+0, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+1, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+2, objectIndexCoords.y), 0), texelFetch (uObjectPerObjectPositionsDecodeMatrix, ivec2(objectIndexCoords.x*4+3, objectIndexCoords.y), 0));"),i.push("uint solid = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+7, objectIndexCoords.y), 0).r;"),i.push("positions[0] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.r, indexPositionV.r), 0));"),i.push("positions[1] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.g, indexPositionV.g), 0));"),i.push("positions[2] = vec3(texelFetch(uTexturePerVertexIdCoordinates, ivec2(indexPositionH.b, indexPositionV.b), 0));"),i.push("uvec4 color = texelFetch (uObjectPerObjectColorsAndFlags, ivec2(objectIndexCoords.x*8+0, objectIndexCoords.y), 0);"),i.push("if (color.a == 0u) {"),i.push(" gl_Position = vec4(3.0, 3.0, 3.0, 1.0);"),i.push(" return;"),i.push("};"),i.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),i.push("vec3 position;"),i.push("position = positions[gl_VertexID % 3];"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (solid != 1u) {"),i.push("if (isPerspectiveMatrix(projMatrix)) {"),i.push("vec3 uCameraEyeRtcInQuantizedSpace = (inverse(sceneModelMatrix * objectDecodeAndInstanceMatrix) * vec4(uCameraEyeRtc, 1)).xyz;"),i.push("if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("viewNormal = -viewNormal;"),i.push("}"),i.push("} else {"),i.push("vec3 viewNormal = -normalize((transpose(inverse(viewMatrix*objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);"),i.push("if (viewNormal.z < 0.0) {"),i.push("position = positions[2 - (gl_VertexID % 3)];"),i.push("}"),i.push("}"),i.push("}"),i.push("vec4 worldPosition = sceneModelMatrix * (objectDecodeAndInstanceMatrix * vec4(position, 1.0)); "),i.push("vec4 viewPosition = viewMatrix * worldPosition; "),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(i.push("vFragDepth = 1.0 + clipPos.w;"),i.push("isPerspective = float (isPerspectiveMatrix(projMatrix));")),i.push("vWorldPosition = worldPosition;"),t&&i.push("vFlags2 = flags2.r;"),i.push("gl_Position = remapClipPos(clipPos);"),i.push("}"),i.push("}"),i}},{key:"_buildFragmentShader",value:function(){var e=this._scene,t=e._sectionPlanesState.getNumAllocatedSectionPlanes()>0,i=[];if(i.push("#version 300 es"),i.push("// TrianglesDataTexturePickNormalsRenderer fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),e.logarithmicDepthBufferEnabled&&(i.push("in float isPerspective;"),i.push("uniform float logDepthBufFC;"),i.push("in float vFragDepth;")),i.push("in vec4 vWorldPosition;"),t){i.push("flat in uint vFlags2;");for(var r=0,s=e._sectionPlanesState.getNumAllocatedSectionPlanes();r 0u;"),i.push(" if (clippable) {"),i.push(" float dist = 0.0;");for(var n=0,o=e._sectionPlanesState.getNumAllocatedSectionPlanes();n 0.0) { "),i.push(" discard;"),i.push(" }"),i.push("}")}return e.logarithmicDepthBufferEnabled&&i.push(" gl_FragDepth = isPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;"),i.push(" vec3 xTangent = dFdx( vWorldPosition.xyz );"),i.push(" vec3 yTangent = dFdy( vWorldPosition.xyz );"),i.push(" vec3 worldNormal = normalize( cross( xTangent, yTangent ) );"),i.push(" outNormal = ivec4(worldNormal * float(".concat($.MAX_INT,"), 1.0);")),i.push("}"),i}},{key:"webglContextRestored",value:function(){this._program=null}},{key:"destroy",value:function(){this._program&&this._program.destroy(),this._program=null}}]),e}(),hc=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"_compile",value:function(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._flatColorRenderer&&!this._flatColorRenderer.getValid()&&(this._flatColorRenderer.destroy(),this._flatColorRenderer=null),this._flatColorRendererWithSAO&&!this._flatColorRendererWithSAO.getValid()&&(this._flatColorRendererWithSAO.destroy(),this._flatColorRendererWithSAO=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._snapRenderer&&!this._snapRenderer.getValid()&&(this._snapRenderer.destroy(),this._snapRenderer=null),this._snapInitRenderer&&!this._snapInitRenderer.getValid()&&(this._snapInitRenderer.destroy(),this._snapInitRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._pickNormalsFlatRenderer&&!1===this._pickNormalsFlatRenderer.getValid()&&(this._pickNormalsFlatRenderer.destroy(),this._pickNormalsFlatRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}},{key:"eagerCreateRenders",value:function(){this._silhouetteRenderer||(this._silhouetteRenderer=new pA(this._scene)),this._pickMeshRenderer||(this._pickMeshRenderer=new EA(this._scene)),this._pickDepthRenderer||(this._pickDepthRenderer=new SA(this._scene)),this._pickNormalsRenderer||(this._pickNormalsRenderer=new cc(this._scene)),this._snapRenderer||(this._snapRenderer=new NA(this._scene)),this._snapInitRenderer||(this._snapInitRenderer=new zA(this._scene)),this._snapRenderer||(this._snapRenderer=new NA(this._scene))}},{key:"colorRenderer",get:function(){return this._colorRenderer||(this._colorRenderer=new lA(this._scene,!1)),this._colorRenderer}},{key:"colorRendererWithSAO",get:function(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new lA(this._scene,!0)),this._colorRendererWithSAO}},{key:"colorQualityRendererWithSAO",get:function(){return this._colorQualityRendererWithSAO}},{key:"silhouetteRenderer",get:function(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pA(this._scene)),this._silhouetteRenderer}},{key:"depthRenderer",get:function(){return this._depthRenderer||(this._depthRenderer=new tc(this._scene)),this._depthRenderer}},{key:"normalsRenderer",get:function(){return this._normalsRenderer||(this._normalsRenderer=new oc(this._scene)),this._normalsRenderer}},{key:"edgesRenderer",get:function(){return this._edgesRenderer||(this._edgesRenderer=new _A(this._scene)),this._edgesRenderer}},{key:"edgesColorRenderer",get:function(){return this._edgesColorRenderer||(this._edgesColorRenderer=new BA(this._scene)),this._edgesColorRenderer}},{key:"pickMeshRenderer",get:function(){return this._pickMeshRenderer||(this._pickMeshRenderer=new EA(this._scene)),this._pickMeshRenderer}},{key:"pickNormalsRenderer",get:function(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new cc(this._scene)),this._pickNormalsRenderer}},{key:"pickNormalsFlatRenderer",get:function(){return this._pickNormalsFlatRenderer||(this._pickNormalsFlatRenderer=new cc(this._scene)),this._pickNormalsFlatRenderer}},{key:"pickDepthRenderer",get:function(){return this._pickDepthRenderer||(this._pickDepthRenderer=new SA(this._scene)),this._pickDepthRenderer}},{key:"snapRenderer",get:function(){return this._snapRenderer||(this._snapRenderer=new NA(this._scene)),this._snapRenderer}},{key:"snapInitRenderer",get:function(){return this._snapInitRenderer||(this._snapInitRenderer=new zA(this._scene)),this._snapInitRenderer}},{key:"occlusionRenderer",get:function(){return this._occlusionRenderer||(this._occlusionRenderer=new JA(this._scene)),this._occlusionRenderer}},{key:"_destroy",value:function(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._flatColorRenderer&&this._flatColorRenderer.destroy(),this._flatColorRendererWithSAO&&this._flatColorRendererWithSAO.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._snapRenderer&&this._snapRenderer.destroy(),this._snapInitRenderer&&this._snapInitRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._pickNormalsFlatRenderer&&this._pickNormalsFlatRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}]),e}(),dc={};var pc=C((function e(){x(this,e),this.positionsCompressed=[],this.lenPositionsCompressed=0,this.metallicRoughness=[],this.indices8Bits=[],this.lenIndices8Bits=0,this.indices16Bits=[],this.lenIndices16Bits=0,this.indices32Bits=[],this.lenIndices32Bits=0,this.edgeIndices8Bits=[],this.lenEdgeIndices8Bits=0,this.edgeIndices16Bits=[],this.lenEdgeIndices16Bits=0,this.edgeIndices32Bits=[],this.lenEdgeIndices32Bits=0,this.perObjectColors=[],this.perObjectPickColors=[],this.perObjectSolid=[],this.perObjectOffsets=[],this.perObjectPositionsDecodeMatrices=[],this.perObjectInstancePositioningMatrices=[],this.perObjectVertexBases=[],this.perObjectIndexBaseOffsets=[],this.perObjectEdgeIndexBaseOffsets=[],this.perTriangleNumberPortionId8Bits=[],this.perTriangleNumberPortionId16Bits=[],this.perTriangleNumberPortionId32Bits=[],this.perEdgeNumberPortionId8Bits=[],this.perEdgeNumberPortionId16Bits=[],this.perEdgeNumberPortionId32Bits=[]})),fc=function(){function e(){x(this,e),this.texturePerObjectColorsAndFlags=null,this.texturePerObjectOffsets=null,this.texturePerObjectInstanceMatrices=null,this.texturePerObjectPositionsDecodeMatrix=null,this.texturePerVertexIdCoordinates=null,this.texturePerPolygonIdPortionIds8Bits=null,this.texturePerPolygonIdPortionIds16Bits=null,this.texturePerPolygonIdPortionIds32Bits=null,this.texturePerEdgeIdPortionIds8Bits=null,this.texturePerEdgeIdPortionIds16Bits=null,this.texturePerEdgeIdPortionIds32Bits=null,this.texturePerPolygonIdIndices8Bits=null,this.texturePerPolygonIdIndices16Bits=null,this.texturePerPolygonIdIndices32Bits=null,this.texturePerPolygonIdEdgeIndices8Bits=null,this.texturePerPolygonIdEdgeIndices16Bits=null,this.texturePerPolygonIdEdgeIndices32Bits=null,this.textureModelMatrices=null}return C(e,[{key:"finalize",value:function(){this.indicesPerBitnessTextures={8:this.texturePerPolygonIdIndices8Bits,16:this.texturePerPolygonIdIndices16Bits,32:this.texturePerPolygonIdIndices32Bits},this.indicesPortionIdsPerBitnessTextures={8:this.texturePerPolygonIdPortionIds8Bits,16:this.texturePerPolygonIdPortionIds16Bits,32:this.texturePerPolygonIdPortionIds32Bits},this.edgeIndicesPerBitnessTextures={8:this.texturePerPolygonIdEdgeIndices8Bits,16:this.texturePerPolygonIdEdgeIndices16Bits,32:this.texturePerPolygonIdEdgeIndices32Bits},this.edgeIndicesPortionIdsPerBitnessTextures={8:this.texturePerEdgeIdPortionIds8Bits,16:this.texturePerEdgeIdPortionIds16Bits,32:this.texturePerEdgeIdPortionIds32Bits}}},{key:"bindCommonTextures",value:function(e,t,i,r,s){this.texturePerObjectPositionsDecodeMatrix.bindTexture(e,t,1),this.texturePerVertexIdCoordinates.bindTexture(e,i,2),this.texturePerObjectColorsAndFlags.bindTexture(e,r,3),this.texturePerObjectInstanceMatrices.bindTexture(e,s,4)}},{key:"bindTriangleIndicesTextures",value:function(e,t,i,r){this.indicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.indicesPerBitnessTextures[r].bindTexture(e,i,6)}},{key:"bindEdgeIndicesTextures",value:function(e,t,i,r){this.edgeIndicesPortionIdsPerBitnessTextures[r].bindTexture(e,t,5),this.edgeIndicesPerBitnessTextures[r].bindTexture(e,i,6)}}]),e}(),vc={sizeDataColorsAndFlags:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(vc,null,4));var e=0;Object.keys(vc).forEach((function(t){t.startsWith("size")&&(e+=vc[t])})),console.log("Total size ".concat(e," bytes (").concat((e/1e3/1e3).toFixed(2)," MB)")),console.log("Avg bytes / triangle: ".concat((e/vc.totalPolygons).toFixed(2)));var t={};Object.keys(vc).forEach((function(i){i.startsWith("size")&&(t[i]="".concat((vc[i]/e*100).toFixed(2)," % of total"))})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};var gc=function(){function e(){x(this,e)}return C(e,[{key:"disableBindedTextureFiltering",value:function(e){e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)}},{key:"createTextureForColorsAndFlags",value:function(e,t,i,r,s,n,o){var a=t.length;this.numPortions=a;var l=4096,u=Math.ceil(a/512);if(0===u)throw"texture height===0";var A=new Uint8Array(16384*u);vc.sizeDataColorsAndFlags+=A.byteLength,vc.numberOfTextures++;for(var c=0;c>24&255,r[c]>>16&255,r[c]>>8&255,255&r[c]],32*c+16),A.set([s[c]>>24&255,s[c]>>16&255,s[c]>>8&255,255&s[c]],32*c+20),A.set([n[c]>>24&255,n[c]>>16&255,n[c]>>8&255,255&n[c]],32*c+24),A.set([o[c]?1:0,0,0,0],32*c+28);var h=e.createTexture();return e.bindTexture(e.TEXTURE_2D,h),e.texStorage2D(e.TEXTURE_2D,1,e.RGBA8UI,l,u),e.texSubImage2D(e.TEXTURE_2D,0,0,0,l,u,e.RGBA_INTEGER,e.UNSIGNED_BYTE,A,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,h,l,u,A)}},{key:"createTextureForObjectOffsets",value:function(e,t){var i=512,r=Math.ceil(t/i);if(0===r)throw"texture height===0";var s=new Float32Array(1536*r).fill(0);vc.sizeDataTextureOffsets+=s.byteLength,vc.numberOfTextures++;var n=e.createTexture();return e.bindTexture(e.TEXTURE_2D,n),e.texStorage2D(e.TEXTURE_2D,1,e.RGB32F,i,r),e.texSubImage2D(e.TEXTURE_2D,0,0,0,i,r,e.RGB,e.FLOAT,s,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),new Wu(e,n,i,r,s)}},{key:"createTextureForInstancingMatrices",value:function(e,t){var i=t.length;if(0===i)throw"num instance matrices===0";var r=2048,s=Math.ceil(i/512),n=new Float32Array(8192*s);vc.numberOfTextures++;for(var o=0;o65536&&vc.cannotCreatePortion.because10BitsObjectId++;var i=this._numPortions+t<=65536,r=void 0!==e.geometryId&&null!==e.geometryId?"".concat(e.geometryId,"#").concat(0):"".concat(e.id,"#").concat(0);if(!this._bucketGeometries[r]){var s=Math.max(this._state.numIndices8Bits,this._state.numIndices16Bits,this._state.numIndices32Bits),n=0,o=0;e.buckets.forEach((function(e){n+=e.positionsCompressed.length/3,o+=e.indices.length/3})),(this._state.numVertices+n>4096*_c||s+o>4096*_c)&&vc.cannotCreatePortion.becauseTextureSize++,i&&(i=this._state.numVertices+n<=4096*_c&&s+o<=4096*_c)}return i}},{key:"createPortion",value:function(e,t){var i=this;if(this._finalized)throw"Already finalized";var r=[];t.buckets.forEach((function(e,s){var n=void 0!==t.geometryId&&null!==t.geometryId?"".concat(t.geometryId,"#").concat(s):"".concat(t.id,"#").concat(s),o=i._bucketGeometries[n];o||(o=i._createBucketGeometry(t,e),i._bucketGeometries[n]=o);var a=i._createSubPortion(t,o,e);r.push(a)}));var s=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(r),this.model.numPortions++,this._meshes.push(e),s}},{key:"_createBucketGeometry",value:function(e,t){if(t.indices){var i=8*Math.ceil(t.indices.length/3/8)*3;vc.overheadSizeAlignementIndices+=2*(i-t.indices.length);var r=new Uint32Array(i);r.fill(0),r.set(t.indices),t.indices=r}if(t.edgeIndices){var s=8*Math.ceil(t.edgeIndices.length/2/8)*2;vc.overheadSizeAlignementEdgeIndices+=2*(s-t.edgeIndices.length);var n=new Uint32Array(s);n.fill(0),n.set(t.edgeIndices),t.edgeIndices=n}var o=t.positionsCompressed,a=t.indices,l=t.edgeIndices,u=this._buffer;u.positionsCompressed.push(o);var A,c=u.lenPositionsCompressed/3,h=o.length/3;u.lenPositionsCompressed+=o.length;var d,p,f=0;a&&(f=a.length/3,h<=256?(d=u.indices8Bits,A=u.lenIndices8Bits/3,u.lenIndices8Bits+=a.length):h<=65536?(d=u.indices16Bits,A=u.lenIndices16Bits/3,u.lenIndices16Bits+=a.length):(d=u.indices32Bits,A=u.lenIndices32Bits/3,u.lenIndices32Bits+=a.length),d.push(a));var v,g=0;l&&(g=l.length/2,h<=256?(v=u.edgeIndices8Bits,p=u.lenEdgeIndices8Bits/2,u.lenEdgeIndices8Bits+=l.length):h<=65536?(v=u.edgeIndices16Bits,p=u.lenEdgeIndices16Bits/2,u.lenEdgeIndices16Bits+=l.length):(v=u.edgeIndices32Bits,p=u.lenEdgeIndices32Bits/2,u.lenEdgeIndices32Bits+=l.length),v.push(l));return this._state.numVertices+=h,vc.numberOfGeometries++,{vertexBase:c,numVertices:h,numTriangles:f,numEdges:g,indicesBase:A,edgeIndicesBase:p}}},{key:"_createSubPortion",value:function(e,t,i,r){var s=e.color;e.metallic,e.roughness;var n,o,a=e.colors,l=e.opacity,u=e.meshMatrix,A=e.pickColor,c=this._buffer,h=this._state;c.perObjectPositionsDecodeMatrices.push(e.positionsDecodeMatrix),c.perObjectInstancePositioningMatrices.push(u||xc),c.perObjectSolid.push(!!e.solid),a?c.perObjectColors.push([255*a[0],255*a[1],255*a[2],255]):s&&c.perObjectColors.push([s[0],s[1],s[2],l]),c.perObjectPickColors.push(A),c.perObjectVertexBases.push(t.vertexBase),n=t.numVertices<=256?h.numIndices8Bits:t.numVertices<=65536?h.numIndices16Bits:h.numIndices32Bits,c.perObjectIndexBaseOffsets.push(n/3-t.indicesBase),o=t.numVertices<=256?h.numEdgeIndices8Bits:t.numVertices<=65536?h.numEdgeIndices16Bits:h.numEdgeIndices32Bits,c.perObjectEdgeIndexBaseOffsets.push(o/2-t.edgeIndicesBase);var d=this._subPortions.length;if(t.numTriangles>0){var p,f=3*t.numTriangles;t.numVertices<=256?(p=c.perTriangleNumberPortionId8Bits,h.numIndices8Bits+=f,vc.totalPolygons8Bits+=t.numTriangles):t.numVertices<=65536?(p=c.perTriangleNumberPortionId16Bits,h.numIndices16Bits+=f,vc.totalPolygons16Bits+=t.numTriangles):(p=c.perTriangleNumberPortionId32Bits,h.numIndices32Bits+=f,vc.totalPolygons32Bits+=t.numTriangles),vc.totalPolygons+=t.numTriangles;for(var v=0;v0){var g,m=2*t.numEdges;t.numVertices<=256?(g=c.perEdgeNumberPortionId8Bits,h.numEdgeIndices8Bits+=m,vc.totalEdges8Bits+=t.numEdges):t.numVertices<=65536?(g=c.perEdgeNumberPortionId16Bits,h.numEdgeIndices16Bits+=m,vc.totalEdges16Bits+=t.numEdges):(g=c.perEdgeNumberPortionId32Bits,h.numEdgeIndices32Bits+=m,vc.totalEdges32Bits+=t.numEdges),vc.totalEdges+=t.numEdges;for(var _=0;_0&&(i.texturePerEdgeIdPortionIds8Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,s.perEdgeNumberPortionId8Bits)),s.perEdgeNumberPortionId16Bits.length>0&&(i.texturePerEdgeIdPortionIds16Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,s.perEdgeNumberPortionId16Bits)),s.perEdgeNumberPortionId32Bits.length>0&&(i.texturePerEdgeIdPortionIds32Bits=this._dtxTextureFactory.createTextureForPackedPortionIds(r,s.perEdgeNumberPortionId32Bits)),s.lenIndices8Bits>0&&(i.texturePerPolygonIdIndices8Bits=this._dtxTextureFactory.createTextureFor8BitIndices(r,s.indices8Bits,s.lenIndices8Bits)),s.lenIndices16Bits>0&&(i.texturePerPolygonIdIndices16Bits=this._dtxTextureFactory.createTextureFor16BitIndices(r,s.indices16Bits,s.lenIndices16Bits)),s.lenIndices32Bits>0&&(i.texturePerPolygonIdIndices32Bits=this._dtxTextureFactory.createTextureFor32BitIndices(r,s.indices32Bits,s.lenIndices32Bits)),s.lenEdgeIndices8Bits>0&&(i.texturePerPolygonIdEdgeIndices8Bits=this._dtxTextureFactory.createTextureFor8BitsEdgeIndices(r,s.edgeIndices8Bits,s.lenEdgeIndices8Bits)),s.lenEdgeIndices16Bits>0&&(i.texturePerPolygonIdEdgeIndices16Bits=this._dtxTextureFactory.createTextureFor16BitsEdgeIndices(r,s.edgeIndices16Bits,s.lenEdgeIndices16Bits)),s.lenEdgeIndices32Bits>0&&(i.texturePerPolygonIdEdgeIndices32Bits=this._dtxTextureFactory.createTextureFor32BitsEdgeIndices(r,s.edgeIndices32Bits,s.lenEdgeIndices32Bits)),i.finalize(),this._buffer=null,this._bucketGeometries={},this._finalized=!0,this._deferredSetFlagsDirty=!1,this._onSceneRendering=this.model.scene.on("rendering",(function(){e._deferredSetFlagsDirty&&e._uploadDeferredFlags(),e._numUpdatesInFrame=0}))}}},{key:"isEmpty",value:function(){return 0===this._numPortions}},{key:"initFlags",value:function(e,t,i){t&Qe&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&We&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&ze&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&Ke&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&je&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&Xe&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),t&He&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),t&Ve&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);this._setFlags(e,t,i,true),this._setFlags2(e,t,true)}},{key:"flushInitFlags",value:function(){this._setDeferredFlags(),this._setDeferredFlags2()}},{key:"setVisible",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Qe?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}},{key:"setHighlighted",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&We?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}},{key:"setXRayed",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&ze?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}},{key:"setSelected",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ke?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}},{key:"setEdges",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Xe?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}},{key:"setClippable",value:function(e,t){if(!this._finalized)throw"Not finalized";t&je?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}},{key:"_beginDeferredFlags",value:function(){this._deferredSetFlagsActive=!0}},{key:"_uploadDeferredFlags",value:function(){if(this._deferredSetFlagsActive=!1,this._deferredSetFlagsDirty){this._deferredSetFlagsDirty=!1;var e=this.model.scene.canvas.gl,t=this._dtxState;e.bindTexture(e.TEXTURE_2D,t.texturePerObjectColorsAndFlags._texture),e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.texturePerObjectColorsAndFlags._textureWidth,t.texturePerObjectColorsAndFlags._textureHeight,e.RGBA_INTEGER,e.UNSIGNED_BYTE,t.texturePerObjectColorsAndFlags._textureData)}}},{key:"setCulled",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&Ve?(this._numCulledLayerPortions+=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions-=this._portionToSubPortionsMap[e].length,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}},{key:"setCollidable",value:function(e,t){if(!this._finalized)throw"Not finalized"}},{key:"setPickable",value:function(e,t,i){if(!this._finalized)throw"Not finalized";t&He?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}},{key:"setColor",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),console.info("_subPortionSetColor write through"),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectColorsAndFlags._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*8,Math.floor(e/512),1,1,r.RGBA_INTEGER,r.UNSIGNED_BYTE,bc)}},{key:"setTransparent",value:function(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}},{key:"_setFlags",value:function(e,t,i){for(var r=arguments.length>3&&void 0!==arguments[3]&&arguments[3],s=this._portionToSubPortionsMap[e],n=0,o=s.length;n3&&void 0!==arguments[3]&&arguments[3];if(!this._finalized)throw"Not finalized";var s,n,o=!!(t&Qe),a=!!(t&ze),l=!!(t&We),u=!!(t&Ke),A=!!(t&Xe),c=!!(t&He),h=!!(t&Ve);s=!o||h||a||l&&!this.model.scene.highlightMaterial.glowThrough||u&&!this.model.scene.selectedMaterial.glowThrough?ao.NOT_RENDERED:i?ao.COLOR_TRANSPARENT:ao.COLOR_OPAQUE,n=!o||h?ao.NOT_RENDERED:u?ao.SILHOUETTE_SELECTED:l?ao.SILHOUETTE_HIGHLIGHTED:a?ao.SILHOUETTE_XRAYED:ao.NOT_RENDERED;var d=0;d=!o||h?ao.NOT_RENDERED:u?ao.EDGES_SELECTED:l?ao.EDGES_HIGHLIGHTED:a?ao.EDGES_XRAYED:A?i?ao.EDGES_COLOR_TRANSPARENT:ao.EDGES_COLOR_OPAQUE:ao.NOT_RENDERED;var p=o&&!h&&c?ao.PICK:ao.NOT_RENDERED,f=this._dtxState,v=this.model.scene.canvas.gl;bc[0]=s,bc[1]=n,bc[2]=d,bc[3]=p,f.texturePerObjectColorsAndFlags._textureData.set(bc,32*e+8),this._deferredSetFlagsActive||r?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),v.bindTexture(v.TEXTURE_2D,f.texturePerObjectColorsAndFlags._texture),v.texSubImage2D(v.TEXTURE_2D,0,e%512*8+2,Math.floor(e/512),1,1,v.RGBA_INTEGER,v.UNSIGNED_BYTE,bc))}},{key:"_setDeferredFlags",value:function(){}},{key:"_setFlags2",value:function(e,t){for(var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=this._portionToSubPortionsMap[e],s=0,n=r.length;s2&&void 0!==arguments[2]&&arguments[2];if(!this._finalized)throw"Not finalized";var r=t&je?255:0,s=this._dtxState,n=this.model.scene.canvas.gl;bc[0]=r,bc[1]=0,bc[2]=1,bc[3]=2,s.texturePerObjectColorsAndFlags._textureData.set(bc,32*e+12),this._deferredSetFlagsActive||i?this._deferredSetFlagsDirty=!0:(++this._numUpdatesInFrame>=10&&this._beginDeferredFlags(),n.bindTexture(n.TEXTURE_2D,s.texturePerObjectColorsAndFlags._texture),n.texSubImage2D(n.TEXTURE_2D,0,e%512*8+3,Math.floor(e/512),1,1,n.RGBA_INTEGER,n.UNSIGNED_BYTE,bc))}},{key:"_setDeferredFlags2",value:function(){}},{key:"setOffset",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectOffsets._texture),r.texSubImage2D(r.TEXTURE_2D,0,0,e,1,1,r.RGB,r.FLOAT,wc))}},{key:"setMatrix",value:function(e,t){for(var i=this._portionToSubPortionsMap[e],r=0,s=i.length;r=10&&this._beginDeferredFlags(),r.bindTexture(r.TEXTURE_2D,i.texturePerObjectInstanceMatrices._texture),r.texSubImage2D(r.TEXTURE_2D,0,e%512*4,Math.floor(e/512),4,1,r.RGBA,r.FLOAT,yc))}},{key:"drawColorOpaque",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?this._renderers.colorRendererWithSAO&&this._renderers.colorRendererWithSAO.drawLayer(t,this,ao.COLOR_OPAQUE):this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"_updateBackfaceCull",value:function(e,t){var i=this.model.backfaces||e.sectioned;if(t.backfaces!==i){var r=t.gl;i?r.disable(r.CULL_FACE):r.enable(r.CULL_FACE),t.backfaces=i}}},{key:"drawColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.colorRenderer&&this._renderers.colorRenderer.drawLayer(t,this,ao.COLOR_TRANSPARENT))}},{key:"drawDepth",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.depthRenderer&&this._renderers.depthRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._renderers.normalsRenderer&&this._renderers.normalsRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawSilhouetteXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_XRAYED))}},{key:"drawSilhouetteHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_HIGHLIGHTED))}},{key:"drawSilhouetteSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.silhouetteRenderer&&this._renderers.silhouetteRenderer.drawLayer(t,this,ao.SILHOUETTE_SELECTED))}},{key:"drawEdgesColorOpaque",value:function(e,t){this.model.scene.logarithmicDepthBufferEnabled?this.model.scene._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),this.model.scene._loggedWarning=!0):this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,ao.EDGES_COLOR_OPAQUE)}},{key:"drawEdgesColorTransparent",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._renderers.edgesColorRenderer&&this._renderers.edgesColorRenderer.drawLayer(t,this,ao.EDGES_COLOR_TRANSPARENT)}},{key:"drawEdgesHighlighted",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_HIGHLIGHTED)}},{key:"drawEdgesSelected",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_SELECTED)}},{key:"drawEdgesXRayed",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._renderers.edgesRenderer&&this._renderers.edgesRenderer.drawLayer(t,this,ao.EDGES_XRAYED)}},{key:"drawOcclusion",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.occlusionRenderer&&this._renderers.occlusionRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"drawShadow",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.shadowRenderer&&this._renderers.shadowRenderer.drawLayer(t,this,ao.COLOR_OPAQUE))}},{key:"setPickMatrices",value:function(e,t){}},{key:"drawPickMesh",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickMeshRenderer&&this._renderers.pickMeshRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawPickDepths",value:function(e,t){0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickDepthRenderer&&this._renderers.pickDepthRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawSnapInit",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapInitRenderer&&this._renderers.snapInitRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawSnap",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.snapRenderer&&this._renderers.snapRenderer.drawLayer(t,this,ao.PICK))}},{key:"drawPickNormals",value:function(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._renderers.pickNormalsRenderer&&this._renderers.pickNormalsRenderer.drawLayer(t,this,ao.PICK))}},{key:"destroy",value:function(){if(!this._destroyed){var e=this._state;e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),this.model.scene.off(this._onSceneRendering),e.destroy(),this._destroyed=!0}}}]),e}(),Cc=function(){function e(t){x(this,e),this.id=t.id,this.colorTexture=t.colorTexture,this.metallicRoughnessTexture=t.metallicRoughnessTexture,this.normalsTexture=t.normalsTexture,this.emissiveTexture=t.emissiveTexture,this.occlusionTexture=t.occlusionTexture}return C(e,[{key:"destroy",value:function(){}}]),e}(),Mc=function(){function e(t){x(this,e),this.id=t.id,this.texture=t.texture}return C(e,[{key:"destroy",value:function(){this.texture&&(this.texture.destroy(),this.texture=null)}}]),e}(),Ec={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={}}},Fc=function(){function e(t,i,r){x(this,e),this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=t,this.onProgress=i,this.onError=r}return C(e,[{key:"itemStart",value:function(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}},{key:"itemEnd",value:function(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}},{key:"itemError",value:function(e){void 0!==this.onError&&this.onError(e)}},{key:"resolveURL",value:function(e){return this.urlModifier?this.urlModifier(e):e}},{key:"setURLModifier",value:function(e){return this.urlModifier=e,this}},{key:"addHandler",value:function(e,t){return this.handlers.push(e,t),this}},{key:"removeHandler",value:function(e){var t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}},{key:"getHandler",value:function(e){for(var t=0,i=this.handlers.length;t0&&void 0!==arguments[0]?arguments[0]:4;x(this,e),this.pool=t,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}return C(e,[{key:"_initWorker",value:function(e){if(!this.workers[e]){var t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}},{key:"_getIdleWorker",value:function(){for(var e=0;e0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),Lc++}return this._transcoderPending}},{key:"transcode",value:function(e,t){var i=this,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return new Promise((function(s,n){var o=r;i._init().then((function(){return i._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:o},e)})).then((function(e){var i=e.data,r=i.mipmaps,o=(i.width,i.height,i.format),a=i.type,l=i.error,u=i.dfdTransferFn,A=i.dfdFlags;if("error"===a)return n(l);t.setCompressedData({mipmaps:r,props:{format:o,minFilter:1===r.length?1006:1008,magFilter:1===r.length?1006:1008,encoding:2===u?3001:3e3,premultiplyAlpha:!!(1&A)}}),s()}))}))}},{key:"destroy",value:function(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),Lc--}}]),e}();Rc.BasisFormat={ETC1S:0,UASTC_4x4:1},Rc.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},Rc.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},Rc.BasisWorker=function(){var e,t,i,r=_EngineFormat,s=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(o){var A,c=o.data;switch(c.type){case"init":e=c.config,A=c.transcoderBinary,t=new Promise((function(e){i={wasmBinary:A,onRuntimeInitialized:e},BASIS(i)})).then((function(){i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((function(){try{for(var t=function(t){var o=new i.KTX2File(new Uint8Array(t));function A(){o.close(),o.delete()}if(!o.isValid())throw A(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");var c=o.isUASTC()?n.UASTC_4x4:n.ETC1S,h=o.getWidth(),d=o.getHeight(),p=o.getLevels(),f=o.getHasAlpha(),v=o.getDFDTransferFunc(),g=o.getDFDFlags(),m=function(t,i,o,A){for(var c,h,d=t===n.ETC1S?a:l,p=0;p=e)){Vc=new Uint32Array(e);for(var t=0;t=e)){Vc=new Uint32Array(e);for(var t=0;t>t;i.sort(Gc);for(var a=new Int32Array(e.length),l=0,u=i.length;le[r+1]){var o=e[r];e[r]=e[r+1],e[r+1]=o}Wc=new Int32Array(e),t.sort(Kc);for(var a=new Int32Array(e.length),l=0,u=t.length;l0)for(var s=i._meshes,r=0,n=s.length;r0)for(var o=this._meshes,a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._dtxEnabled=s.scene.dtxEnabled&&!1!==r.dtxEnabled,s._enableVertexWelding=!1,s._enableIndexBucketing=!1,s._vboBatchingLayerScratchMemory=oo(),s._textureTranscoder=r.textureTranscoder||Oc(s.scene.viewer),s._maxGeometryBatchSize=r.maxGeometryBatchSize,s._aabb=$.collapseAABB3(),s._aabbDirty=!0,s._quantizationRanges={},s._vboInstancingLayers={},s._vboBatchingLayers={},s._dtxLayers={},s._meshList=[],s.layerList=[],s._entityList=[],s._geometries={},s._dtxBuckets={},s._textures={},s._textureSets={},s._transforms={},s._meshes={},s._unusedMeshes={},s._entities={},s.renderFlags=new Kr,s.numGeometries=0,s.numPortions=0,s.numVisibleLayerPortions=0,s.numTransparentLayerPortions=0,s.numXRayedLayerPortions=0,s.numHighlightedLayerPortions=0,s.numSelectedLayerPortions=0,s.numEdgesLayerPortions=0,s.numPickableLayerPortions=0,s.numClippableLayerPortions=0,s.numCulledLayerPortions=0,s.numEntities=0,s._numTriangles=0,s._numLines=0,s._numPoints=0,s._edgeThreshold=r.edgeThreshold||10,s._origin=$.vec3(r.origin||[0,0,0]),s._position=$.vec3(r.position||[0,0,0]),s._rotation=$.vec3(r.rotation||[0,0,0]),s._quaternion=$.vec4(r.quaternion||[0,0,0,1]),s._conjugateQuaternion=$.vec4(r.quaternion||[0,0,0,1]),r.rotation&&$.eulerToQuaternion(s._rotation,"XYZ",s._quaternion),s._scale=$.vec3(r.scale||[1,1,1]),s._worldRotationMatrix=$.mat4(),s._worldRotationMatrixConjugate=$.mat4(),s._matrix=$.mat4(),s._matrixDirty=!0,s._rebuildMatrices(),s._worldNormalMatrix=$.mat4(),$.inverseMat4(s._matrix,s._worldNormalMatrix),$.transposeMat4(s._worldNormalMatrix),(r.matrix||r.position||r.rotation||r.scale||r.quaternion)&&(s._viewMatrix=$.mat4(),s._viewNormalMatrix=$.mat4(),s._viewMatrixDirty=!0,s._matrixNonIdentity=!0),s._opacity=1,s._colorize=[1,1,1],s._saoEnabled=!1!==r.saoEnabled,s._pbrEnabled=!1!==r.pbrEnabled,s._colorTextureEnabled=!1!==r.colorTextureEnabled,s._isModel=r.isModel,s._isModel&&s.scene._registerModel(b(s)),s._onCameraViewMatrix=s.scene.camera.on("matrix",(function(){s._viewMatrixDirty=!0})),s._meshesWithDirtyMatrices=[],s._numMeshesWithDirtyMatrices=0,s._onTick=s.scene.on("tick",(function(){for(;s._numMeshesWithDirtyMatrices>0;)s._meshesWithDirtyMatrices[--s._numMeshesWithDirtyMatrices]._updateMatrix()})),s._createDefaultTextureSet(),s.visible=r.visible,s.culled=r.culled,s.pickable=r.pickable,s.clippable=r.clippable,s.collidable=r.collidable,s.castsShadow=r.castsShadow,s.receivesShadow=r.receivesShadow,s.xrayed=r.xrayed,s.highlighted=r.highlighted,s.selected=r.selected,s.edges=r.edges,s.colorize=r.colorize,s.opacity=r.opacity,s.backfaces=r.backfaces,s}return C(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new Mc({id:"defaultColorTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Mc({id:"defaultMetalRoughTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Mc({id:"defaultNormalsTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),s=new Mc({id:"defaultEmissiveTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),r=new Mc({id:"defaultOcclusionTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=s,this._textures.defaultOcclusionTexture=r,this._textureSets.defaultTextureSet=new Cc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:s,occlusionTexture:r})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||Ah),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&($.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}},{key:"rotationMatrixConjugate",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),A=0,c=l.length;A>24&255,r=i>>16&255,n=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,n,r,s]),e.solid="solid"===e.primitive,t.origin=$.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,s=e.buckets.length;i>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,s=e.textureSetId||"-",r=e.geometryId,n="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(s,".").concat(r),o=this._vboInstancingLayers[n];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new nl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new nl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new Gl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new Uu({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[n]=o,this.layerList.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=$.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=$.createUUID()),void 0!==e.meshIds){var t=0;this._visible&&!1!==e.visible&&(t|=Qe),this._pickable&&!1!==e.pickable&&(t|=He),this._culled&&!1!==e.culled&&(t|=Ve),this._clippable&&!1!==e.clippable&&(t|=je),this._collidable&&!1!==e.collidable&&(t|=Ge),this._edges&&!1!==e.edges&&(t|=Xe),this._xrayed&&!1!==e.xrayed&&(t|=ze),this._highlighted&&!1!==e.highlighted&&(t|=We),this._selected&&!1!==e.selected&&(t|=Ke),e.flags=t,this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,s=e.meshIds.length;it.sortId?1:0}));for(var o=0,a=this.layerList.length;o0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t0){var t="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(var n=0;n0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var s=this.scene.highlightMaterial._state;s.fill&&(s.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),s.edges&&(s.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e){for(var t=this.renderFlags,i=0,s=t.visibleLayers.length;i2&&void 0!==arguments[2]&&arguments[2],s=e.positionsCompressed||[],r=zc(e.indices||[],t),n=Xc(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function s(i,s){return i!==e?e-i:s!==t?t-s:0}for(var r=0,o=(n.length>>1)-1;r<=o;){var a=o+r>>1,l=s(n[2*a],n[2*a+1]);if(l>0)r=a+1;else{if(!(l<0))return a;o=a-1}}return-r-1}var a=new Int32Array(n.length/2);a.fill(0);var l=s.length/3;if(l>8*(1<h.maxNumPositions&&(h=c()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(s[3*v]),h.positionsCompressed.push(s[3*v+1]),h.positionsCompressed.push(s[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(s[3*g]),h.positionsCompressed.push(s[3*g+1]),h.positionsCompressed.push(s[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(s[3*m]),h.positionsCompressed.push(s[3*m+1]),h.positionsCompressed.push(s[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]]))}var y=t/8*2,b=t/8,w=2*s.length+(r.length+n.length)*y,B=0;return s.length,A.forEach((function(e){B+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),B>w?[e]:(i&&Yc(A,e),A)}({positionsCompressed:s,indices:r,edgeIndices:n},s.length/3>65536?16:8):o=[{positionsCompressed:s,indices:r,edgeIndices:n}];return o}var ph=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,e,r))._positions=r.positions||[],r.indices)s._indices=r.indices;else{s._indices=[];for(var n=0,o=s._positions.length/3-1;n1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"BCFViewpoints",e,r)).originatingSystem=r.originatingSystem||"xeokit.io",s.authoringTool=r.authoringTool||"xeokit.io",s}return C(i,[{key:"getViewpoint",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.viewer.scene,s=i.camera,r=i.realWorldOffset,n=!0===t.reverseClippingPlanes,o={},a=$.normalizeVec3($.subVec3(s.look,s.eye,$.vec3())),l=s.eye,u=s.up;s.yUp&&(a=wh(a),l=wh(l),u=wh(u));var A=yh($.addVec3(l,r));"ortho"===s.projection?o.orthogonal_camera={camera_view_point:A,camera_direction:yh(a),camera_up_vector:yh(u),view_to_world_scale:s.ortho.scale}:o.perspective_camera={camera_view_point:A,camera_direction:yh(a),camera_up_vector:yh(u),field_of_view:s.perspective.fov};var c=i.sectionPlanes;for(var d in c)if(c.hasOwnProperty(d)){var p=c[d];if(!p.active)continue;var f=p.pos,v=void 0;v=n?$.negateVec3(p.dir,$.vec3()):p.dir,s.yUp&&(f=wh(f),v=wh(v)),$.addVec3(f,r),f=yh(f),v=yh(v),o.clipping_planes||(o.clipping_planes=[]),o.clipping_planes.push({location:f,direction:v})}var g=i.lineSets;for(var m in g)if(g.hasOwnProperty(m)){var _=g[m];o.lines||(o.lines=[]);for(var y=_.positions,b=_.indices,w=0,B=b.length/2;w1&&void 0!==arguments[1]?arguments[1]:{};if(e){var s=this.viewer,r=s.scene,n=r.camera,o=!1!==i.rayCast,a=!1!==i.immediate,l=!1!==i.reset,u=r.realWorldOffset,A=!0===i.reverseClippingPlanes;if(r.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.length>0&&e.clipping_planes.forEach((function(e){var t=bh(e.location,fh),i=bh(e.direction,fh);A&&$.negateVec3(i),$.subVec3(t,u),n.yUp&&(t=Bh(t),i=Bh(i)),new hn(r,{pos:t,dir:i})})),r.clearLines(),e.lines&&e.lines.length>0){var c=[],h=[],d=0;e.lines.forEach((function(e){e.start_point&&e.end_point&&(c.push(e.start_point.x),c.push(e.start_point.y),c.push(e.start_point.z),c.push(e.end_point.x),c.push(e.end_point.y),c.push(e.end_point.z),h.push(d++),h.push(d++))})),new ph(r,{positions:c,indices:h,clippable:!1,collidable:!0})}if(r.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){var t=e.bitmap_type||"jpg",i=e.bitmap_data,s=bh(e.location,vh),o=bh(e.normal,gh),a=bh(e.up,mh),l=e.height||1;t&&i&&s&&o&&a&&(n.yUp&&(s=Bh(s),o=Bh(o),a=Bh(a)),new $n(r,{src:i,type:t,pos:s,normal:o,up:a,clippable:!1,collidable:!0,height:l}))})),l&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),r.setObjectsHighlighted(r.highlightedObjectIds,!1),r.setObjectsSelected(r.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(r.setObjectsVisible(r.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!1}))}))):(r.setObjectsVisible(r.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!0}))})));var p=e.components.visibility.view_setup_hints;p&&(!1===p.spaces_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==p.spaces_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcSpace"),!0),p.space_boundaries_visible,!1===p.openings_visible&&r.setObjectsVisible(s.metaScene.getObjectIDsByType("IfcOpening"),!0),p.space_boundaries_translucent,void 0!==p.openings_translucent&&r.setObjectsXRayed(s.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(r.setObjectsSelected(r.selectedObjectIds,!1),e.components.selection.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.selected=!0}))}))),e.components.translucency&&(r.setObjectsXRayed(r.xrayedObjectIds,!1),e.components.translucency.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.xrayed=!0}))}))),e.components.coloring&&e.components.coloring.forEach((function(e){var s=e.color,r=0,n=!1;8===s.length&&((r=parseInt(s.substring(0,2),16)/256)<=1&&r>=.95&&(r=1),s=s.substring(2),n=!0);var o=[parseInt(s.substring(0,2),16)/256,parseInt(s.substring(2,4),16)/256,parseInt(s.substring(4,6),16)/256];e.components.map((function(e){return t._withBCFComponent(i,e,(function(e){e.colorize=o,n&&(e.opacity=r)}))}))}))}if(e.perspective_camera||e.orthogonal_camera){var f,v,g,m;if(e.perspective_camera?(f=bh(e.perspective_camera.camera_view_point,fh),v=bh(e.perspective_camera.camera_direction,fh),g=bh(e.perspective_camera.camera_up_vector,fh),n.perspective.fov=e.perspective_camera.field_of_view,m="perspective"):(f=bh(e.orthogonal_camera.camera_view_point,fh),v=bh(e.orthogonal_camera.camera_direction,fh),g=bh(e.orthogonal_camera.camera_up_vector,fh),n.ortho.scale=e.orthogonal_camera.view_to_world_scale,m="ortho"),$.subVec3(f,u),n.yUp&&(f=Bh(f),v=Bh(v),g=Bh(g)),o){var _=r.pick({pickSurface:!0,origin:f,direction:v});v=_?_.worldPos:$.addVec3(f,v,fh)}else v=$.addVec3(f,v,fh);a?(n.eye=f,n.look=v,n.up=g,n.projection=m):s.cameraFlight.flyTo({eye:f,look:v,up:g,duration:i.duration,projection:m})}}}},{key:"_withBCFComponent",value:function(e,t,i){var s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){var n=t.authoring_tool_id,o=r.objects[n];if(o)return void i(o);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[n])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}if(t.ifc_guid){var a=t.ifc_guid,l=r.objects[a];if(l)return void i(l);if(e.updateCompositeObjects)if(s.metaScene.metaObjects[a])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(a),i);Object.keys(r.models).forEach((function(t){var n=$.globalizeObjectId(t,a),o=r.objects[n];o?i(o):e.updateCompositeObjects&&s.metaScene.metaObjects[n]&&r.withObjects(s.metaScene.getObjectIDsInSubtree(n),i)}))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}();function yh(e){return{x:e[0],y:e[1],z:e[2]}}function bh(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function wh(e){return new Float64Array([e[0],-e[2],e[1]])}function Bh(e){return new Float64Array([e[0],e[2],-e[1]])}function xh(e){var t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}var Ph=$.vec3(),Ch=function(e,t,i,s){var r=e-i,n=t-s;return Math.sqrt(r*r+n*n)};var Mh=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";s._eventSubs={};var n=s.plugin.viewer.scene;s._originMarker=new et(n,r.origin),s._targetMarker=new et(n,r.target),s._originWorld=$.vec3(),s._targetWorld=$.vec3(),s._wp=new Float64Array(24),s._vp=new Float64Array(24),s._pp=new Float64Array(24),s._cp=new Float64Array(8),s._xAxisLabelCulled=!1,s._yAxisLabelCulled=!1,s._zAxisLabelCulled=!1,s._color=r.color||s.plugin.defaultColor;var o=r.onMouseOver?function(e){r.onMouseOver(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=r.onMouseLeave?function(e){r.onMouseLeave(e,b(s)),s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},u=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},c=r.onContextMenu?function(e){r.onContextMenu(e,b(s))}:null,h=function(e){s.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return s._originDot=new st(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._targetDot=new st(s._container,{fillColor:s._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthWire=new it(s._container,{color:s._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisWire=new it(s._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisWire=new it(s._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisWire=new it(s._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._lengthLabel=new rt(s._container,{fillColor:s._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._xAxisLabel=new rt(s._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._yAxisLabel=new rt(s._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._zAxisLabel=new rt(s._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),s._measurementOrientation="Horizontal",s._wpDirty=!1,s._vpDirty=!1,s._cpDirty=!1,s._sectionPlanesDirty=!0,s._visible=!1,s._originVisible=!1,s._targetVisible=!1,s._wireVisible=!1,s._axisVisible=!1,s._xAxisVisible=!1,s._yAxisVisible=!1,s._zAxisVisible=!1,s._axisEnabled=!0,s._xLabelEnabled=!1,s._yLabelEnabled=!1,s._zLabelEnabled=!1,s._lengthLabelEnabled=!1,s._labelsVisible=!1,s._labelsOnWires=!1,s._clickable=!1,s._originMarker.on("worldPos",(function(e){s._originWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._targetMarker.on("worldPos",(function(e){s._targetWorld.set(e||[0,0,0]),s._wpDirty=!0,s._needUpdate(0)})),s._onViewMatrix=n.camera.on("viewMatrix",(function(){s._vpDirty=!0,s._needUpdate(0)})),s._onProjMatrix=n.camera.on("projMatrix",(function(){s._cpDirty=!0,s._needUpdate()})),s._onCanvasBoundary=n.canvas.on("boundary",(function(){s._cpDirty=!0,s._needUpdate(0)})),s._onMetricsUnits=n.metrics.on("units",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsScale=n.metrics.on("scale",(function(){s._cpDirty=!0,s._needUpdate()})),s._onMetricsOrigin=n.metrics.on("origin",(function(){s._cpDirty=!0,s._needUpdate()})),s._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){s._sectionPlanesDirty=!0,s._needUpdate()})),s.approximate=r.approximate,s.visible=r.visible,s.originVisible=r.originVisible,s.targetVisible=r.targetVisible,s.wireVisible=r.wireVisible,s.axisVisible=r.axisVisible,s.xAxisVisible=r.xAxisVisible,s.yAxisVisible=r.yAxisVisible,s.zAxisVisible=r.zAxisVisible,s.xLabelEnabled=r.xLabelEnabled,s.yLabelEnabled=r.yLabelEnabled,s.zLabelEnabled=r.zLabelEnabled,s.lengthLabelEnabled=r.lengthLabelEnabled,s.labelsVisible=r.labelsVisible,s.labelsOnWires=r.labelsOnWires,s.useRotationAdjustment=r.useRotationAdjustment,s}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}var t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var s=this._pp,r=this._cp,n=e.canvas.canvas.getBoundingClientRect(),o=this._container.getBoundingClientRect(),a=n.top-o.top,l=n.left-o.left,u=e.canvas.boundary,A=u[2],c=u[3],h=0,d=this.plugin.viewer.scene.metrics,p=d.scale,f=d.units,v=d.unitsInfo[f].abbrev,g=0,m=s.length;g1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene))._canvasToPagePos=r.canvasToPagePos,s.pointerLens=r.pointerLens,s._active=!1,s._currentDistanceMeasurement=null,s._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},s._initMarkerDiv(),s._onCameraControlHoverSnapOrSurface=null,s._onCameraControlHoverSnapOrSurfaceOff=null,s._onMouseDown=null,s._onMouseUp=null,s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s._snapping=!1!==r.snapping,s._mouseState=0,s._attachPlugin(e,r),s}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this._markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this._markerDiv||this._initMarkerDiv(),this.fire("activated",!0);var t=this.distanceMeasurementsPlugin,i=this.scene,s=t.viewer.cameraControl,r=i.canvas.canvas;i.input;var n,o,a=!1,l=$.vec3(),u=$.vec2(),A=null;this._mouseState=0;var c=function e(t){return t.offsetTop+(t.offsetParent&&t.offsetParent!==r.parentNode&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&t.offsetParent!==r.parentNode&&e(t.offsetParent))},d=$.vec2();this._onCameraControlHoverSnapOrSurface=s.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){var i=t.snappedCanvasPos||t.canvasPos;a=!0,l.set(t.worldPos),u.set(t.canvasPos),0===e._mouseState?(e._canvasToPagePos?(e._canvasToPagePos(r,i,d),e._markerDiv.style.left="".concat(d[0]-5,"px"),e._markerDiv.style.top="".concat(d[1]-5,"px")):(e._markerDiv.style.left="".concat(h(r)+i[0]-5,"px"),e._markerDiv.style.top="".concat(c(r)+i[1]-5,"px")),e._markerDiv.style.background="pink",t.snappedToVertex||t.snappedToEdge?(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,e.pointerLens.snapped=!0),e._markerDiv.style.background="greenyellow",e._markerDiv.style.border="2px solid green"):(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.canvasPos,e.pointerLens.snapped=!1),e._markerDiv.style.background="pink",e._markerDiv.style.border="2px solid red"),A=t.entity):(e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px"),r.style.cursor="pointer",e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.wireVisible=e._currentDistanceMeasurementInitState.wireVisible,e._currentDistanceMeasurement.axisVisible=e._currentDistanceMeasurementInitState.axisVisible&&e.distanceMeasurementsPlugin.defaultAxisVisible,e._currentDistanceMeasurement.xAxisVisible=e._currentDistanceMeasurementInitState.xAxisVisible&&e.distanceMeasurementsPlugin.defaultXAxisVisible,e._currentDistanceMeasurement.yAxisVisible=e._currentDistanceMeasurementInitState.yAxisVisible&&e.distanceMeasurementsPlugin.defaultYAxisVisible,e._currentDistanceMeasurement.zAxisVisible=e._currentDistanceMeasurementInitState.zAxisVisible&&e.distanceMeasurementsPlugin.defaultZAxisVisible,e._currentDistanceMeasurement.targetVisible=e._currentDistanceMeasurementInitState.targetVisible,e._currentDistanceMeasurement.target.worldPos=l.slice(),e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px")})),r.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(n=e.clientX,o=e.clientY)}),r.addEventListener("mouseup",this._onMouseUp=function(i){1===i.which&&(i.clientX>n+20||i.clientXo+20||i.clientY1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"DistanceMeasurements",e))._pointerLens=r.pointerLens,s._container=r.container||document.body,s._defaultControl=null,s._measurements={},s.labelMinAxisLength=r.labelMinAxisLength,s.defaultVisible=!1!==r.defaultVisible,s.defaultOriginVisible=!1!==r.defaultOriginVisible,s.defaultTargetVisible=!1!==r.defaultTargetVisible,s.defaultWireVisible=!1!==r.defaultWireVisible,s.defaultXLabelEnabled=!1!==r.defaultXLabelEnabled,s.defaultYLabelEnabled=!1!==r.defaultYLabelEnabled,s.defaultZLabelEnabled=!1!==r.defaultZLabelEnabled,s.defaultLengthLabelEnabled=!1!==r.defaultLengthLabelEnabled,s.defaultLabelsVisible=!1!==r.defaultLabelsVisible,s.defaultAxisVisible=!1!==r.defaultAxisVisible,s.defaultXAxisVisible=!1!==r.defaultXAxisVisible,s.defaultYAxisVisible=!1!==r.defaultYAxisVisible,s.defaultZAxisVisible=!1!==r.defaultZAxisVisible,s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.zIndex=r.zIndex||1e4,s.defaultLabelsOnWires=!1!==r.defaultLabelsOnWires,s.useRotationAdjustment=void 0!==r.useRotationAdjustment&&!1!==r.useRotationAdjustment,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),distanceMeasurement:t,measurement:t,event:e})},s}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"pointerLens",get:function(){return this._pointerLens}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new Fh(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"labelMinAxisLength",get:function(){return this._labelMinAxisLength},set:function(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}},{key:"useRotationAdjustment",get:function(){return this._useRotationAdjustment},set:function(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,s=t.target,r=new Mh(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},target:{entity:s.entity,worldPos:s.worldPos},visible:t.visible,wireVisible:t.wireVisible,axisVisible:!1!==t.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==t.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==t.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisibld:!1!==t.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==t.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==t.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==t.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==t.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==t.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:t.originVisible,targetVisible:t.targetVisible,color:t.color,labelsOnWires:!1!==t.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[r.id]=r,r.clickable=!0,r.on("destroyed",(function(){delete e._measurements[r.id]})),this.fire("measurementCreated",r),r}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e.viewer.scene)).pointerLens=r.pointerLens,s.pointerCircle=new De(e.viewer),s._active=!1;var n=document.createElement("div"),o=s.scene.canvas.canvas;return o.parentNode.insertBefore(n,o),n.style.background="black",n.style.border="2px solid blue",n.style.borderRadius="10px",n.style.width="5px",n.style.height="5px",n.style.margin="-200px -200px",n.style.zIndex="100",n.style.position="absolute",n.style.pointerEvents="none",s.markerDiv=n,s._currentDistanceMeasurement=null,s._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},s._onCanvasTouchStart=null,s._onCanvasTouchEnd=null,s._longTouchTimeoutMs=300,s._snapping=!1!==r.snapping,s._touchState=0,s._attachPlugin(e,r),s}return C(i,[{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){var t=this.plugin,i=this.scene,s=i.canvas.canvas;t.pointerLens;var r=$.vec3(),n=20,o=null;this._touchState=0;var a=$.vec2(),l=$.vec2(),u=$.vec2(),A=null,c=function(){e.plugin.viewer.cameraControl.active=!1},h=function(){e.plugin.viewer.cameraControl.active=!0};s.addEventListener("touchstart",this._onCanvasTouchStart=function(s){var u=s.touches.length;if(1===u){var d=s.touches[0],p=d.clientX,f=d.clientY;switch(a.set([p,f]),l.set([p,f]),e._touchState){case 0:if(1!==u&&null!==o)return o&&(clearTimeout(o),o=null),e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.destroy(),e._currentDistanceMeasurement=null),h(),void(e._touchState=0);var v=i.pick({canvasPos:l,snapping:e._snapping,snapToEdge:e._snapping});if(v&&v.snapped)r.set(v.worldPos),e.pointerCircle.start(v.snappedCanvasPos);else{var g=i.pick({canvasPos:l,pickSurface:!0});if(!g||!g.worldPos)return;r.set(g.worldPos),e.pointerCircle.start(g.canvasPos)}o=setTimeout((function(){1!==u||l[0]>a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||da[1]+n||pa[0]+n||da[1]+n||p1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,"FastNav",e))._hideColorTexture=!1!==r.hideColorTexture,s._hidePBR=!1!==r.hidePBR,s._hideSAO=!1!==r.hideSAO,s._hideEdges=!1!==r.hideEdges,s._hideTransparentObjects=!!r.hideTransparentObjects,s._scaleCanvasResolution=!!r.scaleCanvasResolution,s._defaultScaleCanvasResolutionFactor=r.defaultScaleCanvasResolutionFactor||1,s._scaleCanvasResolutionFactor=r.scaleCanvasResolutionFactor||.6,s._delayBeforeRestore=!1!==r.delayBeforeRestore,s._delayBeforeRestoreSeconds=r.delayBeforeRestoreSeconds||.5;var n=1e3*s._delayBeforeRestoreSeconds,o=!1,a=function(){n=1e3*s._delayBeforeRestoreSeconds,o||(e.scene._renderer.setColorTextureEnabled(!s._hideColorTexture),e.scene._renderer.setPBREnabled(!s._hidePBR),e.scene._renderer.setSAOEnabled(!s._hideSAO),e.scene._renderer.setTransparentEnabled(!s._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!s._hideEdges),s._scaleCanvasResolution?e.scene.canvas.resolutionScale=s._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=s._defaultScaleCanvasResolutionFactor,o=!0)},l=function(){e.scene.canvas.resolutionScale=s._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),o=!1};s._onCanvasBoundary=e.scene.canvas.on("boundary",a),s._onCameraMatrix=e.scene.camera.on("matrix",a),s._onSceneTick=e.scene.on("tick",(function(e){o&&(n-=e.deltaTime,(!s._delayBeforeRestore||n<=0)&&l())}));var u=!1;return s._onSceneMouseDown=e.scene.input.on("mousedown",(function(){u=!0})),s._onSceneMouseUp=e.scene.input.on("mouseup",(function(){u=!1})),s._onSceneMouseMove=e.scene.input.on("mousemove",(function(){u&&a()})),s}return C(i,[{key:"hideColorTexture",get:function(){return this._hideColorTexture},set:function(e){this._hideColorTexture=e}},{key:"hidePBR",get:function(){return this._hidePBR},set:function(e){this._hidePBR=e}},{key:"hideSAO",get:function(){return this._hideSAO},set:function(e){this._hideSAO=e}},{key:"hideEdges",get:function(){return this._hideEdges},set:function(e){this._hideEdges=e}},{key:"hideTransparentObjects",get:function(){return this._hideTransparentObjects},set:function(e){this._hideTransparentObjects=!1!==e}},{key:"scaleCanvasResolution",get:function(){return this._scaleCanvasResolution},set:function(e){this._scaleCanvasResolution=e}},{key:"defaultScaleCanvasResolutionFactor",get:function(){return this._defaultScaleCanvasResolutionFactor},set:function(e){this._defaultScaleCanvasResolutionFactor=e||1}},{key:"scaleCanvasResolutionFactor",get:function(){return this._scaleCanvasResolutionFactor},set:function(e){this._scaleCanvasResolutionFactor=e||.6}},{key:"delayBeforeRestore",get:function(){return this._delayBeforeRestore},set:function(e){this._delayBeforeRestore=e}},{key:"delayBeforeRestoreSeconds",get:function(){return this._delayBeforeRestoreSeconds},set:function(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Sh=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getMetaModel",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLTF",value:function(e,t,i){le.loadArraybuffer(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLB",value:function(e,t,i){le.loadArraybuffer(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getArrayBuffer",value:function(e,t,i,s){!function(e,t,i,s){var r=function(){};i=i||r,s=s||r;var n=/^data:(.*?)(;base64)?,(.*)$/,o=t.match(n);if(o){var a=!!o[2],l=o[3];l=window.decodeURIComponent(l),a&&(l=window.atob(l));try{for(var u=new ArrayBuffer(l.length),A=new Uint8Array(u),c=0;c0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=t.messages,this.locale=t.locale}return C(e,[{key:"messages",set:function(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}},{key:"loadMessages",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)this._messages[t]=e[t];this.messages=this._messages}},{key:"clearMessages",value:function(){this.messages={}}},{key:"locales",get:function(){return this._locales}},{key:"locale",get:function(){return this._locale},set:function(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}},{key:"translate",value:function(e,t){var i=this._messages[this._locale];if(!i)return null;var s=Lh(e,i);return s?t?Rh(s,t):s:null}},{key:"translatePlurals",value:function(e,t,i){var s=this._messages[this._locale];if(!s)return null;var r=Lh(e,s);return(r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one)?(r=Rh(r,[t]),i&&(r=Rh(r,i)),r):null}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);var s=this._eventSubs[e];if(s)for(var r in s){if(s.hasOwnProperty(r))s[r].callback(t)}}},{key:"on",value:function(e,t){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new Q),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});var i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);var s=this._eventSubIDMap.addItem();i[s]={callback:t},this._eventSubEvents[s]=e;var r=this._events[e];return void 0!==r&&t(r),s}},{key:"off",value:function(e){if(null!=e&&this._eventSubEvents){var t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];var i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}}]),e}();function Lh(e,t){if(t[e])return t[e];for(var i=e.split("."),s=t,r=0,n=i.length;s&&r1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}var Uh=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).t=r.t,s}return C(i,[{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"tangent",get:function(){return this.getTangent(this._t)}},{key:"length",get:function(){var e=this._getLengths();return e[e.length-1]}},{key:"getTangent",value:function(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),n=this.getPoint(s),o=$.subVec3(n,r,[]);return $.normalizeVec3(o,[])}},{key:"getPointAt",value:function(e){var t=this.getUToTMapping(e);return this.getPoint(t)}},{key:"getPoints",value:function(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}},{key:"_getLengths",value:function(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),n=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=$.lenVec3($.subVec3(t,r,[])),s.push(n),r=t;return this.cacheArcLengths=s,s}},{key:"_updateArcLengths",value:function(){this.needsUpdate=!0,this._getLengths()}},{key:"getUToTMapping",value:function(e,t){var i,s=this._getLengths(),r=0,n=s.length;i=t||e*s[n-1];for(var o,a=0,l=n-1;a<=l;)if((o=s[r=Math.floor(a+(l-a)/2)]-i)<0)a=r+1;else{if(!(o>0)){l=r;break}l=r-1}if(s[r=l]===i)return r/(n-1);var u=s[r];return(r+(i-u)/(s[r+1]-u))/(n-1)}}]),i}(),Oh=function(e){g(i,Uh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).points=r.points,s.t=r.t,s}return C(i,[{key:"points",get:function(){return this._points},set:function(e){this._points=e||[]}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,n=t[0===s?s:s-1],o=t[s],a=t[s>t.length-2?t.length-1:s+1],l=t[s>t.length-3?t.length-1:s+2],u=$.vec3();return u[0]=$.catmullRomInterpolate(n[0],o[0],a[0],l[0],r),u[1]=$.catmullRomInterpolate(n[1],o[1],a[1],l[1],r),u[2]=$.catmullRomInterpolate(n[2],o[2],a[2],l[2],r),u}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}},{key:"getJSON",value:function(){return{points:points,t:this._t}}}]),i}(),Nh=$.vec3(),Qh=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._frames=[],s._eyeCurve=new Oh(b(s)),s._lookCurve=new Oh(b(s)),s._upCurve=new Oh(b(s)),r.frames&&(s.addFrames(r.frames),s.smoothFrameTimes(1)),s}return C(i,[{key:"type",get:function(){return"CameraPath"}},{key:"frames",get:function(){return this._frames}},{key:"eyeCurve",get:function(){return this._eyeCurve}},{key:"lookCurve",get:function(){return this._lookCurve}},{key:"upCurve",get:function(){return this._upCurve}},{key:"saveFrame",value:function(e){var t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}},{key:"addFrame",value:function(e,t,i,s){var r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}},{key:"addFrames",value:function(e){for(var t,i=0,s=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Nh),t.look=this._lookCurve.getPoint(e,Nh),t.up=this._upCurve.getPoint(e,Nh)}},{key:"sampleFrame",value:function(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}},{key:"smoothFrameTimes",value:function(e){if(0!==this._frames.length){var t=$.vec3(),i=0;this._frames[0].t=0;for(var s=[],r=1,n=this._frames.length;r1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._look1=$.vec3(),s._eye1=$.vec3(),s._up1=$.vec3(),s._look2=$.vec3(),s._eye2=$.vec3(),s._up2=$.vec3(),s._orthoScale1=1,s._orthoScale2=1,s._flying=!1,s._flyEyeLookUp=!1,s._flyingEye=!1,s._flyingLook=!1,s._callback=null,s._callbackScope=null,s._time1=null,s._time2=null,s.easing=!1!==r.easing,s.duration=r.duration,s.fit=r.fit,s.fitFOV=r.fitFOV,s.trail=r.trail,s}return C(i,[{key:"type",get:function(){return"CameraFlightAnimation"}},{key:"flyTo",value:function(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;var s,r,n,o,a,l=this.scene.camera,u=!!e.projection&&e.projection!==l.projection;if(this._eye1[0]=l.eye[0],this._eye1[1]=l.eye[1],this._eye1[2]=l.eye[2],this._look1[0]=l.look[0],this._look1[1]=l.look[1],this._look1[2]=l.look[2],this._up1[0]=l.up[0],this._up1[1]=l.up[1],this._up1[2]=l.up[2],this._orthoScale1=l.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)s=e.aabb;else if(6===e.length)s=e;else if(e.eye&&e.look||e.up)r=e.eye,n=e.look,o=e.up;else if(e.eye)r=e.eye;else if(e.look)n=e.look;else{var A=e;if((le.isNumeric(A)||le.isString(A))&&(a=A,!(A=this.scene.components[a])))return this.error("Component not found: "+le.inQuotes(a)),void(t&&(i?t.call(i):t()));u||(s=A.aabb||this.scene.aabb)}var c=e.poi;if(s){if(s[3]=1;e>1&&(e=1);var s=this.easing?i._ease(e,0,1,1):e,r=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?($.subVec3(r.eye,r.look,zh),r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,jh),r.look=$.subVec3(jh,zh,Hh)):this._flyingLook&&(r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Hh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Gh)):this._flyingEyeLookUp&&(r.eye=$.lerpVec3(s,0,1,this._eye1,this._eye2,jh),r.look=$.lerpVec3(s,0,1,this._look1,this._look2,Hh),r.up=$.lerpVec3(s,0,1,this._up1,this._up2,Gh)),this._projection2){var n="ortho"===this._projection2?i._easeOutExpo(e,0,1,1):i._easeInCubic(e,0,1,1);r.customProjection.matrix=$.lerpMat4(n,0,1,this._projMatrix1,this._projMatrix2)}else r.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return r.ortho.scale=this._orthoScale2,void this.stop();_e.scheduleTask(this._update,this)}}},{key:"stop",value:function(){if(this._flying){this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);var e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}}},{key:"cancel",value:function(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}},{key:"duration",get:function(){return this._duration/1e3},set:function(e){this._duration=e?1e3*e:500,this.stop()}},{key:"fit",get:function(){return this._fit},set:function(e){this._fit=!1!==e}},{key:"fitFOV",get:function(){return this._fitFOV},set:function(e){this._fitFOV=e||45}},{key:"trail",get:function(){return this._trail},set:function(e){this._trail=!!e}},{key:"destroy",value:function(){this.stop(),f(w(i.prototype),"destroy",this).call(this)}}],[{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"_easeInCubic",value:function(e,t,i,s){return i*(e/=s)*e*e+t}},{key:"_easeOutExpo",value:function(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}}]),i}(),Kh=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._cameraFlightAnimation=new Wh(b(s)),s._t=0,s.state=i.SCRUBBING,s._playingFromT=0,s._playingToT=0,s._playingRate=r.playingRate||1,s._playingDir=1,s._lastTime=null,s.cameraPath=r.cameraPath,s._tick=s.scene.on("tick",s._updateT,b(s)),s}return C(i,[{key:"type",get:function(){return"CameraPathAnimation"}},{key:"_updateT",value:function(){var e=this._cameraPath;if(e){var t,s,r=performance.now(),n=this._lastTime?.001*(r-this._lastTime):0;if(this._lastTime=r,0!==n)switch(this.state){case i.SCRUBBING:return;case i.PLAYING:if(this._t+=this._playingRate*n,0===(t=this._cameraPath.frames.length)||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=i.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case i.PLAYING_TO:s=this._t+this._playingRate*n*this._playingDir,(this._playingDir<0&&s<=this._playingToT||this._playingDir>0&&s>=this._playingToT)&&(s=this._playingToT,this.state=i.SCRUBBING,this.fire("stopped")),this._t=s,e.loadFrame(this._t)}}}},{key:"_ease",value:function(e,t,i,s){return-i*(e/=s)*(e-2)+t}},{key:"cameraPath",get:function(){return this._cameraPath},set:function(e){this._cameraPath=e}},{key:"rate",get:function(){return this._playingRate},set:function(e){this._playingRate=e}},{key:"play",value:function(){this._cameraPath&&(this._lastTime=null,this.state=i.PLAYING)}},{key:"playToT",value:function(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=i.PLAYING_TO)}},{key:"playToFrame",value:function(e){var t=this._cameraPath;if(t){var i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}}},{key:"flyToFrame",value:function(e,t){var s=this._cameraPath;if(s){var r=s.frames[e];r?(this.state=i.SCRUBBING,this._cameraFlightAnimation.flyTo(r,t)):this.error("flyToFrame - frame index out of range: "+e)}}},{key:"scrubToT",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=i.SCRUBBING))}},{key:"scrubToFrame",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(t.frames[e]?(t.loadFrame(this._t),this.state=i.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)))}},{key:"stop",value:function(){this.state=i.SCRUBBING,this.fire("stopped")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene.off(this._tick)}}]),i}();Kh.STOPPED=0,Kh.SCRUBBING=1,Kh.PLAYING=2,Kh.PLAYING_TO=3;var Xh=$.vec3(),Yh=$.vec3();$.vec3();var Jh=$.vec3([0,-1,0]),Zh=$.vec4([0,0,0,1]),qh=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new On(b(s)),s._plane=new nn(b(s),{geometry:new Ti(b(s),Yn({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Ni(b(s),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:s._texture,emissiveMap:s._texture,backfaces:!0}),clippable:r.clippable}),s._grid=new nn(b(s),{geometry:new Ti(b(s),Xn({size:1,divisions:10})),material:new Ni(b(s),{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:r.clippable}),s._node=new wn(b(s),{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[s._plane,s._grid]}),s._gridVisible=!1,s.visible=!0,s.gridVisible=r.gridVisible,s.position=r.position,s.rotation=r.rotation,s.dir=r.dir,s.size=r.size,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"visible",get:function(){return this._plane.visible},set:function(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}},{key:"gridVisible",get:function(){return this._gridVisible},set:function(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"position",get:function(){return this._pos},set:function(e){this._pos.set(e||[0,0,0]),Re(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}},{key:"rotation",get:function(){return this._node.rotation},set:function(e){this._node.rotation=e}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"dir",get:function(){return this._dir},set:function(e){if(this._dir.set(e||[0,0,-1]),e){var t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];$.subVec3(t,this.position,Xh);var s=-$.dotVec3(i,Xh);$.normalizeVec3(i),$.mulVec3Scalar(i,s,Yh),$.vec3PairToQuaternion(Jh,e,Zh),this._node.quaternion=Zh}}},{key:"collidable",get:function(){return this._node.collidable},set:function(e){this._node.collidable=!1!==e}},{key:"clippable",get:function(){return this._node.clippable},set:function(e){this._node.clippable=!1!==e}},{key:"pickable",get:function(){return this._node.pickable},set:function(e){this._node.pickable=!1!==e}},{key:"opacity",get:function(){return this._node.opacity},set:function(e){this._node.opacity=e}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}},{key:"_updatePlaneSizeFromImage",value:function(){var e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){var s=i/t;this._node.scale=[e,1,e*s]}else{var r=t/i;this._node.scale=[e*r,1,e]}}}]),i}(),$h=function(e){g(i,yi);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i);var n=b(s=t.call(this,e,r));s._shadowRenderBuf=null,s._shadowViewMatrix=null,s._shadowProjMatrix=null,s._shadowViewMatrixDirty=!0,s._shadowProjMatrixDirty=!0;var o=s.scene.camera,a=s.scene.canvas;return s._onCameraViewMatrix=o.on("viewMatrix",(function(){s._shadowViewMatrixDirty=!0})),s._onCameraProjMatrix=o.on("projMatrix",(function(){s._shadowProjMatrixDirty=!0})),s._onCanvasBoundary=a.on("boundary",(function(){s._shadowProjMatrixDirty=!0})),s._state=new qt({type:"point",pos:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:r.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(n._shadowViewMatrixDirty){n._shadowViewMatrix||(n._shadowViewMatrix=$.identityMat4());var e=n._state.pos,t=o.look,i=o.up;$.lookAtMat4v(e,t,i,n._shadowViewMatrix),n._shadowViewMatrixDirty=!1}return n._shadowViewMatrix},getShadowProjMatrix:function(){if(n._shadowProjMatrixDirty){n._shadowProjMatrix||(n._shadowProjMatrix=$.identityMat4());var e=n.scene.canvas.canvas;$.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,n._shadowProjMatrix),n._shadowProjMatrixDirty=!1}return n._shadowProjMatrix},getShadowRenderBuf:function(){return n._shadowRenderBuf||(n._shadowRenderBuf=new Wt(n.scene.canvas.canvas,n.scene.canvas.gl,{size:[1024,1024]})),n._shadowRenderBuf}}),s.pos=r.pos,s.color=r.color,s.intensity=r.intensity,s.constantAttenuation=r.constantAttenuation,s.linearAttenuation=r.linearAttenuation,s.quadraticAttenuation=r.quadraticAttenuation,s.castsShadow=r.castsShadow,s.scene._lightCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function ed(e){return 0==(e&e-1)}function td(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var id=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i);var n=(s=t.call(this,e,r)).scene.canvas.gl;return s._state=new qt({texture:new Dn({gl:n,target:n.TEXTURE_CUBE_MAP}),flipY:s._checkFlipY(r.minFilter),encoding:s._checkEncoding(r.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),s._src=r.src,s._images=[],s._loadSrc(r.src),se.memory.textures++,s}return C(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var s=!1,r=0,n=function(n){var o,a,l=new Image;l.onload=(o=l,a=n,function(){if(!s&&(o=function(e){if(!ed(e.width)||!ed(e.height)){var t=document.createElement("canvas");t.width=td(e.width),t.height=td(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++r)){var e=t._state.texture;e||(e=new Dn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){s=!0},l.src=e[n]},o=0;o1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).scene._lightsState.addReflectionMap(s._state),s.scene._reflectionMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),rd=function(e){g(i,id);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).scene._lightMapCreated(b(s)),s}return C(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),nd=function(e){g(i,et);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,{entity:r.entity,occludable:r.occludable,worldPos:r.worldPos}))._occluded=!1,s._visible=!0,s._src=null,s._image=null,s._pos=$.vec3(),s._origin=$.vec3(),s._rtcPos=$.vec3(),s._dir=$.vec3(),s._size=1,s._imageSize=$.vec2(),s._texture=new On(b(s),{src:r.src}),s._geometry=new Ti(b(s),{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),s._mesh=new nn(b(s),{geometry:s._geometry,material:new Ni(b(s),{ambient:[.9,.3,.9],shininess:30,diffuseMap:s._texture,backfaces:!0}),scale:[1,1,1],position:r.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),s.visible=!0,s.collidable=r.collidable,s.clippable=r.clippable,s.pickable=r.pickable,s.opacity=r.opacity,s.size=r.size,r.image?s.image=r.image:s.src=r.src,s}return C(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,f(w(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}]),i}(),od=function(){function e(t){x(this,e),this._eye=$.vec3(),this._look=$.vec3(),this._up=$.vec3(),this._projection={},t&&this.saveCamera(t)}return C(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(function(){r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}]),e}(),ad=$.vec3(),ld=function(){function e(t){if(x(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return C(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?le.apply(i,{}):null;for(var s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,A=!i||i.colorize,c=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.v3=r.v3,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||$.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=$.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=$.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),hd=function(e){g(i,Uh);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._cachedLengths=[],s._dirty=!0,s._curves=[],s._t=0,s._dirtySubs=[],s._destroyedSubs=[],s.curves=r.curves||[],s.t=r.t,s}return C(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r=i){var n=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(n)}r++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r)).v0=r.v0,s.v1=r.v1,s.v2=r.v2,s.t=r.t,s}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=$.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=$.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),pd=function(e){g(i,hh);var t=_(i);function i(e){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),t.call(this,e,s)}return C(i)}(),fd=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e,r))._skyboxMesh=new nn(b(s),{geometry:new Ti(b(s),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Ni(b(s),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new On(b(s),{src:r.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:r.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),s.size=r.size,s.active=r.active,s}return C(i,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),i}(),vd=function(){function e(){x(this,e)}return C(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),gd=$.vec4(),md=$.vec4(),_d=$.vec3(),yd=$.vec3(),bd=$.vec3(),wd=$.vec4(),Bd=$.vec4(),xd=$.vec4(),Pd=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var s=!1,r=this._scene.camera;if(e){var n=$.subVec3(e,r.eye,_d);s=$.lenVec3(n)0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new Ni(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=$.lookAtMat4v(e.eye,e.look,e.worldUp);$.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=$.distVec3(e.eye,i),t=$.inverseMat4(t);var s=$.transformVec3(t,this._cameraOffset),r=$.vec3();if($.subVec3(e.eye,i,r),$.addVec3(r,s),e.zUp){var n=r[1];r[1]=r[2],r[2]=n}this._radius=$.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=$.normalizeVec3($.subVec3(e.look,e.eye,Cd)),i=$.cross3Vec3(t,e.worldUp,Md);return $.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs($.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),o=[0,0,-1,1],a=$.dotVec4(o,r)/$.dotVec4(o,n),l=Fd;t.project.unproject(e,a,kd,Id,l);var u=$.normalizeVec3($.subVec3(l,t.eye,Cd)),A=$.addVec3(t.eye,$.mulVec3Scalar(u,i,Md),Ed);this.setPivotPos(A)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,s=-e,r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=$.clamp(this._polar,.001,Math.PI-.001);var n=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var o=n[1];n[1]=n[2],n[2]=o}var a=$.lenVec3($.subVec3(i.look,i.eye,$.vec3())),l=this.getPivotPos();$.addVec3(n,l);var u=$.lookAtMat4v(n,l,i.worldUp);u=$.inverseMat4(u);var A=$.transformVec3(u,this._cameraOffset);u[12]-=A[0],u[13]-=A[1],u[14]-=A[2];var c=[u[8],u[9],u[10]];i.eye=[u[12],u[13],u[14]],$.subVec3(i.eye,$.mulVec3Scalar(c,a),i.look),i.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Sd=function(){function e(t,i){x(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=$.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return C(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var s=this.pickResult.canvasPos;if(s[0]===this.pickCursorPos[0]&&s[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var r=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new xt;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),Td=$.vec2(),Ld=function(){function e(t,i,s,r,n){x(this,e),this._scene=t;var o,a,l,u=i.pickController,A=0,c=0,h=0,d=0,p=!1,f=$.vec3(),v=!0,g=this._scene.canvas.canvas,m=[];function _(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];g.style.cursor="move",y(),e&&b()}function y(){A=r.pointerCanvasPos[0],c=r.pointerCanvasPos[1],h=r.pointerCanvasPos[0],d=r.pointerCanvasPos[1]}function b(){u.pickCursorPos=r.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(p=!0,f.set(u.pickResult.worldPos)):p=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!1}}),g.addEventListener("mousedown",this._mouseDownHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:m[t.input.KEY_SHIFT]||s.planView?(o=!0,_()):(o=!0,_(!1));break;case 2:a=!0,_();break;case 3:l=!0,s.panRightClick&&_()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(e){if(s.active&&s.pointerEnabled&&(o||a||l)){var i=t.canvas.boundary,u=i[2],h=i[3],d=r.pointerCanvasPos[0],v=r.pointerCanvasPos[1],g=m[t.input.KEY_SHIFT]||s.planView||!s.panRightClick&&a||s.panRightClick&&l,_=document.pointerLockElement?e.movementX:d-A,y=document.pointerLockElement?e.movementY:v-c;if(g){var b=t.camera;if("perspective"===b.projection){var w=Math.abs(p?$.lenVec3($.subVec3(f,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(b.perspective.fov/2*Math.PI/180);n.panDeltaX+=1.5*_*w/h,n.panDeltaY+=1.5*y*w/h}else n.panDeltaX+=.5*b.ortho.scale*(_/h),n.panDeltaY+=.5*b.ortho.scale*(y/h)}else!o||a||l||s.planView||(s.firstPerson?(n.rotateDeltaY-=_/u*s.dragRotationRate/2,n.rotateDeltaX+=y/h*(s.dragRotationRate/4)):(n.rotateDeltaY-=_/u*(1.5*s.dragRotationRate),n.rotateDeltaX+=y/h*(1.5*s.dragRotationRate)));A=d,c=v}}),g.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){s.active&&s.pointerEnabled&&r.mouseover&&(v=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(s.active&&s.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1}}),g.addEventListener("mouseup",this._mouseUpHandler=function(e){if(s.active&&s.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,s=0,r=0,n=0,o=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,n+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-s,t[1]=e.pageY+o-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Td);var t=Td[0],r=Td[1];Math.abs(t-h)<3&&Math.abs(r-d)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Td,event:e},!0)}g.style.removeProperty("cursor")}}),g.addEventListener("mouseenter",this._mouseEnterHandler=function(){s.active&&s.pointerEnabled});var w=1/60,B=null;g.addEventListener("wheel",this._mouseWheelHandler=function(e){if(s.active&&s.pointerEnabled){var t=performance.now()/1e3,i=null!==B?t-B:0;B=t,i>.05&&(i=.05),i0?i.cameraFlight.flyTo(Vd,(function(){i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(Vd),i.pivotController.getPivoting()&&s.followPointer&&i.pivotController.showPivot())}}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),jd=function(){function e(t,i,s,r,n){var o=this;x(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var A=!1,c=!1,h=this._scene.canvas.canvas,d=function(e){var s;e&&e.worldPos&&(s=e.worldPos);var r=e&&e.entity?e.entity.aabb:t.aabb;if(s){var n=t.camera;$.subVec3(n.eye,n.look,[]),i.cameraFlight.flyTo({aabb:r})}else i.cameraFlight.flyTo({aabb:r})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(s.active&&s.pointerEnabled&&!A&&!c){if(u.hasSubs("rayMove")){var i=$.vec3(),n=$.vec3();$.canvasPosToWorldRay(t.canvas.canvas,t.camera.viewMatrix,t.camera.projMatrix,r.pointerCanvasPos,i,n),u.fire("rayMove",{canvasPos:r.pointerCanvasPos,ray:{origin:i,direction:n,canvasPos:r.pointerCanvasPos}},!0)}var l=u.hasSubs("hover"),h=u.hasSubs("hoverEnter"),d=u.hasSubs("hoverOut"),p=u.hasSubs("hoverOff"),f=u.hasSubs("hoverSurface"),v=u.hasSubs("hoverSnapOrSurface");if(l||h||d||p||f||v)if(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=f,a.scheduleSnapOrPick=v,a.update(),a.pickResult){if(a.pickResult.entity){var g=a.pickResult.entity.id;o._lastPickedEntityId!==g&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=g)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(A=!0),3===e.which&&(c=!0),1===e.which&&s.active&&s.pointerEnabled&&(r.mouseDownClientX=e.clientX,r.mouseDownClientY=e.clientY,r.mouseDownCursorX=r.pointerCanvasPos[0],r.mouseDownCursorY=r.pointerCanvasPos[1],!s.firstPerson&&s.followPointer&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot()):(s.smartPivot?l.setCanvasPivotPos(r.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(A=!1),3===e.which&&(c=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(s.active&&s.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-r.mouseDownClientX)>3||Math.abs(e.clientY-r.mouseDownClientY)>3)))){var n=u.hasSubs("picked"),A=u.hasSubs("pickedNothing"),c=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(s.doublePickFlyTo||h||p||f))return(n||A||c)&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=c,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo,a.schedulePickSurface=c,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!s.firstPerson&&s.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:r.pointerCanvasPos},!0),o._clicks=0}),s.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=r.pointerCanvasPos,a.schedulePickEntity=s.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),s.doublePickFlyTo&&(d(a.pickResult),!s.firstPerson&&s.followPointer)){var m=a.pickResult.entity.aabb,_=$.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:r.pointerCanvasPos},!0),s.doublePickFlyTo&&(d(),!s.firstPerson&&s.followPointer)){var y=t.aabb,b=$.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return C(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Gd=function(){function e(t,i,s,r,n){x(this,e),this._scene=t;var o=t.input,a=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=o.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover&&(a[e]=!0,e===o.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(function(e){s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,e===o.KEY_SHIFT&&(l.style.cursor=null),i.pivotController.getPivoting()&&i.pivotController.endPivot())})),this._onTick=t.on("tick",(function(e){if(s.active&&s.pointerEnabled&&t.input.keyboardEnabled&&r.mouseover){var l=i.cameraControl,A=e.deltaTime/1e3;if(!s.planView){var c=l._isKeyDownForAction(l.ROTATE_Y_POS,a),h=l._isKeyDownForAction(l.ROTATE_Y_NEG,a),d=l._isKeyDownForAction(l.ROTATE_X_POS,a),p=l._isKeyDownForAction(l.ROTATE_X_NEG,a),f=A*s.keyboardRotationRate;(c||h||d||p)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),c?n.rotateDeltaY+=f:h&&(n.rotateDeltaY-=f),d?n.rotateDeltaX+=f:p&&(n.rotateDeltaX-=f),!s.firstPerson&&s.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=l._isKeyDownForAction(l.DOLLY_BACKWARDS,a),g=l._isKeyDownForAction(l.DOLLY_FORWARDS,a);if(v||g){var m=A*s.keyboardDollyRate;!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),g?n.dollyDelta-=m:v&&(n.dollyDelta+=m),u&&(r.followPointerDirty=!0,u=!1)}}var _=l._isKeyDownForAction(l.PAN_FORWARDS,a),y=l._isKeyDownForAction(l.PAN_BACKWARDS,a),b=l._isKeyDownForAction(l.PAN_LEFT,a),w=l._isKeyDownForAction(l.PAN_RIGHT,a),B=l._isKeyDownForAction(l.PAN_UP,a),x=l._isKeyDownForAction(l.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*A*s.keyboardPanRate;(_||y||b||w||B||x)&&(!s.firstPerson&&s.followPointer&&i.pivotController.startPivot(),x?n.panDeltaY+=P:B&&(n.panDeltaY+=-P),w?n.panDeltaX+=-P:b&&(n.panDeltaX+=P),y?n.panDeltaZ+=P:_&&(n.panDeltaZ+=-P))}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),zd=$.vec3(),Wd=function(){function e(t,i,s,r,n){x(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,A=1,c=1,h=null;this._onTick=t.on("tick",(function(){if(s.active&&s.pointerEnabled){var e="default";if(Math.abs(n.dollyDelta)<.001&&(n.dollyDelta=0),Math.abs(n.rotateDeltaX)<.001&&(n.rotateDeltaX=0),Math.abs(n.rotateDeltaY)<.001&&(n.rotateDeltaY=0),0===n.rotateDeltaX&&0===n.rotateDeltaY||(n.dollyDelta=0),s.followPointer){if(--A<=0&&(A=1,0!==n.dollyDelta)){if(0===n.rotateDeltaY&&0===n.rotateDeltaX&&s.followPointer&&r.followPointerDirty&&(a.pickCursorPos=r.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?h=a.pickResult.worldPos:(c=1,h=null),r.followPointerDirty=!1),h){var i=Math.abs($.lenVec3($.subVec3(h,t.camera.eye,zd)));c=i/s.dollyProximityThreshold}cs.longTapRadius||Math.abs(g)>s.longTapRadius)&&(clearTimeout(r.longTouchTimeout),r.longTouchTimeout=null),s.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);n.panDeltaX+=v*_/l*s.touchPanRate,n.panDeltaY+=g*_/l*s.touchPanRate}else n.panDeltaX+=.5*m.ortho.scale*(v/l)*s.touchPanRate,n.panDeltaY+=.5*m.ortho.scale*(g/l)*s.touchPanRate}else n.rotateDeltaY-=v/a*(1*s.dragRotationRate),n.rotateDeltaX+=g/l*(1.5*s.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Yd(y,u),Yd(b,A);var w=$.geometricMeanVec2(h[0],h[1]),B=$.geometricMeanVec2(u,A),x=$.vec2();$.subVec2(w,B,x);var P=x[0],C=x[1],M=t.camera,E=$.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),F=($.distVec2(h[0],h[1])-E)*s.touchDollyRate;if(n.dollyDelta=F,Math.abs(F)<1)if("perspective"===M.projection){var k=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs($.lenVec3($.subVec3(k,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);n.panDeltaX-=P*I/l*s.touchPanRate,n.panDeltaY-=C*I/l*s.touchPanRate}else n.panDeltaX-=.5*M.ortho.scale*(P/l)*s.touchPanRate,n.panDeltaY-=.5*M.ortho.scale*(C/l)*s.touchPanRate;r.pointerCanvasPos=B}for(var D=0;D-1&&t-c<150&&(h>-1&&c-h<325?(Zd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),s.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),s.doublePickFlyTo&&p()),h=-1):$.distVec2(u[0],A)<4&&(Zd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),c=-1),u.length=i.length;for(var d=0,f=i.length;d1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,e,r)).PAN_LEFT=0,s.PAN_RIGHT=1,s.PAN_UP=2,s.PAN_DOWN=3,s.PAN_FORWARDS=4,s.PAN_BACKWARDS=5,s.ROTATE_X_POS=6,s.ROTATE_X_NEG=7,s.ROTATE_Y_POS=8,s.ROTATE_Y_NEG=9,s.DOLLY_FORWARDS=10,s.DOLLY_BACKWARDS=11,s.AXIS_VIEW_RIGHT=12,s.AXIS_VIEW_BACK=13,s.AXIS_VIEW_LEFT=14,s.AXIS_VIEW_FRONT=15,s.AXIS_VIEW_TOP=16,s.AXIS_VIEW_BOTTOM=17,s._keyMap={},s.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},s._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},s._states={pointerCanvasPos:$.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:$.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},s._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var n=s.scene;return s._controllers={cameraControl:b(s),pickController:new Sd(b(s),s._configs),pivotController:new Dd(n,s._configs),panController:new Pd(n),cameraFlight:new Wh(b(s),{duration:.5})},s._handlers=[new Kd(s.scene,s._controllers,s._configs,s._states,s._updates),new Jd(s.scene,s._controllers,s._configs,s._states,s._updates),new Ld(s.scene,s._controllers,s._configs,s._states,s._updates),new Hd(s.scene,s._controllers,s._configs,s._states,s._updates),new jd(s.scene,s._controllers,s._configs,s._states,s._updates),new qd(s.scene,s._controllers,s._configs,s._states,s._updates),new Gd(s.scene,s._controllers,s._configs,s._states,s._updates)],s._cameraUpdater=new Wd(s.scene,s._controllers,s._configs,s._states,s._updates),s.navMode=r.navMode,r.planView&&(s.planView=r.planView),s.constrainVertical=r.constrainVertical,r.keyboardLayout?s.keyboardLayout=r.keyboardLayout:s.keyMap=r.keyMap,s.doublePickFlyTo=r.doublePickFlyTo,s.panRightClick=r.panRightClick,s.active=r.active,s.followPointer=r.followPointer,s.rotationInertia=r.rotationInertia,s.keyboardPanRate=r.keyboardPanRate,s.touchPanRate=r.touchPanRate,s.keyboardRotationRate=r.keyboardRotationRate,s.dragRotationRate=r.dragRotationRate,s.touchDollyRate=r.touchDollyRate,s.dollyInertia=r.dollyInertia,s.dollyProximityThreshold=r.dollyProximityThreshold,s.dollyMinSpeed=r.dollyMinSpeed,s.panInertia=r.panInertia,s.pointerEnabled=!0,s.keyboardDollyRate=r.keyboardDollyRate,s.mouseWheelDollyRate=r.mouseWheelDollyRate,s}return C(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",le.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{var s=e;this._keyMap=s}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(var s=0,r=i.length;s0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),f(w(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,s=e.properties;if(e.propertySets)for(var r=0,n=e.propertySets.length;r0?np(t):null,o=i&&i.length>0?np(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||n&&!n[t.type])&&(i=!1),i&&s.push(t.id);var r=t.children;if(r)for(var a=0,l=r.length;a>t;i.sort(Gc);for(var a=new Int32Array(e.length),l=0,u=i.length;le[s+1]){var o=e[s];e[s]=e[s+1],e[s+1]=o}Wc=new Int32Array(e),t.sort(Kc);for(var a=new Int32Array(e.length),l=0,u=t.length;l0)for(var r=i._meshes,s=0,n=r.length;s0)for(var o=this._meshes,a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).renderOrder=s.renderOrder||0,r._dtxEnabled=r.scene.dtxEnabled&&!1!==s.dtxEnabled,r._enableVertexWelding=!1,r._enableIndexBucketing=!1,r._vboBatchingLayerScratchMemory=oo(),r._textureTranscoder=s.textureTranscoder||Oc(r.scene.viewer),r._maxGeometryBatchSize=s.maxGeometryBatchSize,r._aabb=$.collapseAABB3(),r._aabbDirty=!0,r._quantizationRanges={},r._vboInstancingLayers={},r._vboBatchingLayers={},r._dtxLayers={},r._meshList=[],r.layerList=[],r._entityList=[],r._geometries={},r._dtxBuckets={},r._textures={},r._textureSets={},r._transforms={},r._meshes={},r._unusedMeshes={},r._entities={},r.renderFlags=new Ks,r.numGeometries=0,r.numPortions=0,r.numVisibleLayerPortions=0,r.numTransparentLayerPortions=0,r.numXRayedLayerPortions=0,r.numHighlightedLayerPortions=0,r.numSelectedLayerPortions=0,r.numEdgesLayerPortions=0,r.numPickableLayerPortions=0,r.numClippableLayerPortions=0,r.numCulledLayerPortions=0,r.numEntities=0,r._numTriangles=0,r._numLines=0,r._numPoints=0,r._edgeThreshold=s.edgeThreshold||10,r._origin=$.vec3(s.origin||[0,0,0]),r._position=$.vec3(s.position||[0,0,0]),r._rotation=$.vec3(s.rotation||[0,0,0]),r._quaternion=$.vec4(s.quaternion||[0,0,0,1]),r._conjugateQuaternion=$.vec4(s.quaternion||[0,0,0,1]),s.rotation&&$.eulerToQuaternion(r._rotation,"XYZ",r._quaternion),r._scale=$.vec3(s.scale||[1,1,1]),r._worldRotationMatrix=$.mat4(),r._worldRotationMatrixConjugate=$.mat4(),r._matrix=$.mat4(),r._matrixDirty=!0,r._rebuildMatrices(),r._worldNormalMatrix=$.mat4(),$.inverseMat4(r._matrix,r._worldNormalMatrix),$.transposeMat4(r._worldNormalMatrix),(s.matrix||s.position||s.rotation||s.scale||s.quaternion)&&(r._viewMatrix=$.mat4(),r._viewNormalMatrix=$.mat4(),r._viewMatrixDirty=!0,r._matrixNonIdentity=!0),r._opacity=1,r._colorize=[1,1,1],r._saoEnabled=!1!==s.saoEnabled,r._pbrEnabled=!1!==s.pbrEnabled,r._colorTextureEnabled=!1!==s.colorTextureEnabled,r._isModel=s.isModel,r._isModel&&r.scene._registerModel(b(r)),r._onCameraViewMatrix=r.scene.camera.on("matrix",(function(){r._viewMatrixDirty=!0})),r._meshesWithDirtyMatrices=[],r._numMeshesWithDirtyMatrices=0,r._onTick=r.scene.on("tick",(function(){for(;r._numMeshesWithDirtyMatrices>0;)r._meshesWithDirtyMatrices[--r._numMeshesWithDirtyMatrices]._updateMatrix()})),r._createDefaultTextureSet(),r.visible=s.visible,r.culled=s.culled,r.pickable=s.pickable,r.clippable=s.clippable,r.collidable=s.collidable,r.castsShadow=s.castsShadow,r.receivesShadow=s.receivesShadow,r.xrayed=s.xrayed,r.highlighted=s.highlighted,r.selected=s.selected,r.edges=s.edges,r.colorize=s.colorize,r.opacity=s.opacity,r.backfaces=s.backfaces,r}return C(i,[{key:"_meshMatrixDirty",value:function(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}},{key:"_createDefaultTextureSet",value:function(){var e=new Mc({id:"defaultColorTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})}),t=new Mc({id:"defaultMetalRoughTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,1,1,1]})}),i=new Mc({id:"defaultNormalsTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,0]})}),r=new Mc({id:"defaultEmissiveTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[0,0,0,1]})}),s=new Mc({id:"defaultOcclusionTexture",texture:new Dn({gl:this.scene.canvas.gl,preloadColor:[1,1,1,1]})});this._textures.defaultColorTexture=e,this._textures.defaultMetalRoughTexture=t,this._textures.defaultNormalsTexture=i,this._textures.defaultEmissiveTexture=r,this._textures.defaultOcclusionTexture=s,this._textureSets.defaultTextureSet=new Cc({id:"defaultTextureSet",model:this,colorTexture:e,metallicRoughnessTexture:t,normalsTexture:i,emissiveTexture:r,occlusionTexture:s})}},{key:"isPerformanceModel",get:function(){return!0}},{key:"transforms",get:function(){return this._transforms}},{key:"textures",get:function(){return this._textures}},{key:"textureSets",get:function(){return this._textureSets}},{key:"meshes",get:function(){return this._meshes}},{key:"objects",get:function(){return this._entities}},{key:"origin",get:function(){return this._origin}},{key:"position",get:function(){return this._position},set:function(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotation",get:function(){return this._rotation},set:function(e){this._rotation.set(e||[0,0,0]),$.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"quaternion",get:function(){return this._quaternion},set:function(e){this._quaternion.set(e||[0,0,0,1]),$.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"scale",get:function(){return this._scale},set:function(e){}},{key:"matrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._matrix},set:function(e){this._matrix.set(e||Ah),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}},{key:"rotationMatrix",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrix}},{key:"_rebuildMatrices",value:function(){this._matrixDirty&&($.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),$.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),$.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),$.translateMat4v(this._position,this._matrix),this._matrixDirty=!1)}},{key:"rotationMatrixConjugate",get:function(){return this._matrixDirty&&this._rebuildMatrices(),this._worldRotationMatrixConjugate}},{key:"_setWorldMatrixDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0}},{key:"_transformDirty",value:function(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}},{key:"_sceneModelDirty",value:function(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(var e=0,t=this._entityList.length;e0},set:function(e){e=!1!==e,this._visible=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._xrayed=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._highlighted=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._selected=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!!e,this._edges=e;for(var t=0,i=this._entityList.length;t0},set:function(e){e=!1!==e,this._pickable=e;for(var t=0,i=this._entityList.length;t0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){for(var l=e.colors,u=new Uint8Array(l.length),A=0,c=l.length;A>24&255,s=i>>16&255,n=i>>8&255,o=255&i;switch(e.pickColor=new Uint8Array([o,n,s,r]),e.solid="solid"===e.primitive,t.origin=$.vec3(e.origin),e.type){case 2:t.layer=this._getDTXLayer(e),t.aabb=e.aabb;break;case 1:t.layer=this._getVBOBatchingLayer(e),t.aabb=e.aabb;break;case 0:t.layer=this._getVBOInstancingLayer(e),t.aabb=e.aabb}return e.transform&&(e.meshMatrix=e.transform.worldMatrix),t.portionId=t.layer.createPortion(t,e),this._meshes[e.id]=t,this._unusedMeshes[e.id]=t,this._meshList.push(t),t}},{key:"_getNumPrimitives",value:function(e){var t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(var i=0,r=e.buckets.length;i>>0).toString(16)}},{key:"_getVBOInstancingLayer",value:function(e){var t=this,i=e.origin,r=e.textureSetId||"-",s=e.geometryId,n="".concat(Math.round(i[0]),".").concat(Math.round(i[1]),".").concat(Math.round(i[2]),".").concat(r,".").concat(s),o=this._vboInstancingLayers[n];if(o)return o;for(var a=e.textureSet,l=e.geometry;!o;)switch(l.primitive){case"triangles":case"surface":o=new nl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!1});break;case"solid":o=new nl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0,solid:!0});break;case"lines":o=new Gl({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0});break;case"points":o=new Uu({model:t,textureSet:a,geometry:l,origin:i,layerIndex:0})}return this._vboInstancingLayers[n]=o,this.layerList.push(o),o}},{key:"createEntity",value:function(e){if(void 0===e.id?e.id=$.createUUID():this.scene.components[e.id]&&(this.error("Scene already has a Component with this ID: ".concat(e.id," - will assign random ID")),e.id=$.createUUID()),void 0!==e.meshIds){var t=0;this._visible&&!1!==e.visible&&(t|=Qe),this._pickable&&!1!==e.pickable&&(t|=He),this._culled&&!1!==e.culled&&(t|=Ve),this._clippable&&!1!==e.clippable&&(t|=je),this._collidable&&!1!==e.collidable&&(t|=Ge),this._edges&&!1!==e.edges&&(t|=Xe),this._xrayed&&!1!==e.xrayed&&(t|=ze),this._highlighted&&!1!==e.highlighted&&(t|=We),this._selected&&!1!==e.selected&&(t|=Ke),e.flags=t,this._createEntity(e)}else this.error("Config missing: meshIds")}},{key:"_createEntity",value:function(e){for(var t=[],i=0,r=e.meshIds.length;it.sortId?1:0}));for(var o=0,a=this.layerList.length;o0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}},{key:"_updateRenderFlagsVisibleLayers",value:function(){var e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(var t=0,i=this.layerList.length;t0){var t="".concat(this.id,"-dummyEntityForUnusedMeshes");this.warn('Creating dummy SceneModelEntity "'.concat(t,'" for unused SceneMeshes: [').concat(e.join(","),"]")),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}},{key:"_getActiveSectionPlanesForLayer",value:function(e){var t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,r=i.length,s=e.layerIndex*r;if(r>0)for(var n=0;n0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){var t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0)this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions0&&(e.edgesTransparent=!0));if(this.numSelectedLayerPortions>0){var i=this.scene.selectedMaterial._state;i.fill&&(i.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),i.edges&&(i.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){var r=this.scene.highlightMaterial._state;r.fill&&(r.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),r.edges&&(r.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}},{key:"drawColorOpaque",value:function(e,t){for(var i=this.renderFlags,r=0,s=i.visibleLayers.length;r2&&void 0!==arguments[2]&&arguments[2],r=e.positionsCompressed||[],s=zc(e.indices||[],t),n=Xc(e.edgeIndices||[]);function o(e,t){if(e>t){var i=e;e=t,t=i}function r(i,r){return i!==e?e-i:r!==t?t-r:0}for(var s=0,o=(n.length>>1)-1;s<=o;){var a=o+s>>1,l=r(n[2*a],n[2*a+1]);if(l>0)s=a+1;else{if(!(l<0))return a;o=a-1}}return-s-1}var a=new Int32Array(n.length/2);a.fill(0);var l=r.length/3;if(l>8*(1<h.maxNumPositions&&(h=c()),h.bucketNumber>8)return[e];-1===u[v]&&(u[v]=h.numPositions++,h.positionsCompressed.push(r[3*v]),h.positionsCompressed.push(r[3*v+1]),h.positionsCompressed.push(r[3*v+2])),-1===u[g]&&(u[g]=h.numPositions++,h.positionsCompressed.push(r[3*g]),h.positionsCompressed.push(r[3*g+1]),h.positionsCompressed.push(r[3*g+2])),-1===u[m]&&(u[m]=h.numPositions++,h.positionsCompressed.push(r[3*m]),h.positionsCompressed.push(r[3*m+1]),h.positionsCompressed.push(r[3*m+2])),h.indices.push(u[v]),h.indices.push(u[g]),h.indices.push(u[m]);var _=void 0;(_=o(v,g))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(v,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]])),(_=o(g,m))>=0&&0===a[_]&&(a[_]=1,h.edgeIndices.push(u[n[2*_]]),h.edgeIndices.push(u[n[2*_+1]]))}var y=t/8*2,b=t/8,w=2*r.length+(s.length+n.length)*y,B=0;return r.length,A.forEach((function(e){B+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*b,e.positionsCompressed.length})),B>w?[e]:(i&&Yc(A,e),A)}({positionsCompressed:r,indices:s,edgeIndices:n},r.length/3>65536?16:8):o=[{positionsCompressed:r,indices:s,edgeIndices:n}];return o}var ph=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,e,s))._positions=s.positions||[],s.indices)r._indices=s.indices;else{r._indices=[];for(var n=0,o=r._positions.length/3-1;n1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"BCFViewpoints",e,s)).originatingSystem=s.originatingSystem||"xeokit.io",r.authoringTool=s.authoringTool||"xeokit.io",r}return C(i,[{key:"getViewpoint",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},i=this.viewer.scene,r=i.camera,s=i.realWorldOffset,n=!0===t.reverseClippingPlanes,o={},a=$.normalizeVec3($.subVec3(r.look,r.eye,$.vec3())),l=r.eye,u=r.up;r.yUp&&(a=wh(a),l=wh(l),u=wh(u));var A=yh($.addVec3(l,s));"ortho"===r.projection?o.orthogonal_camera={camera_view_point:A,camera_direction:yh(a),camera_up_vector:yh(u),view_to_world_scale:r.ortho.scale}:o.perspective_camera={camera_view_point:A,camera_direction:yh(a),camera_up_vector:yh(u),field_of_view:r.perspective.fov};var c=i.sectionPlanes;for(var d in c)if(c.hasOwnProperty(d)){var p=c[d];if(!p.active)continue;var f=p.pos,v=void 0;v=n?$.negateVec3(p.dir,$.vec3()):p.dir,r.yUp&&(f=wh(f),v=wh(v)),$.addVec3(f,s),f=yh(f),v=yh(v),o.clipping_planes||(o.clipping_planes=[]),o.clipping_planes.push({location:f,direction:v})}var g=i.lineSets;for(var m in g)if(g.hasOwnProperty(m)){var _=g[m];o.lines||(o.lines=[]);for(var y=_.positions,b=_.indices,w=0,B=b.length/2;w1&&void 0!==arguments[1]?arguments[1]:{};if(e){var r=this.viewer,s=r.scene,n=s.camera,o=!1!==i.rayCast,a=!1!==i.immediate,l=!1!==i.reset,u=s.realWorldOffset,A=!0===i.reverseClippingPlanes;if(s.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.length>0&&e.clipping_planes.forEach((function(e){var t=bh(e.location,fh),i=bh(e.direction,fh);A&&$.negateVec3(i),$.subVec3(t,u),n.yUp&&(t=Bh(t),i=Bh(i)),new hn(s,{pos:t,dir:i})})),s.clearLines(),e.lines&&e.lines.length>0){var c=[],h=[],d=0;e.lines.forEach((function(e){e.start_point&&e.end_point&&(c.push(e.start_point.x),c.push(e.start_point.y),c.push(e.start_point.z),c.push(e.end_point.x),c.push(e.end_point.y),c.push(e.end_point.z),h.push(d++),h.push(d++))})),new ph(s,{positions:c,indices:h,clippable:!1,collidable:!0})}if(s.clearBitmaps(),e.bitmaps&&e.bitmaps.length>0&&e.bitmaps.forEach((function(e){var t=e.bitmap_type||"jpg",i=e.bitmap_data,r=bh(e.location,vh),o=bh(e.normal,gh),a=bh(e.up,mh),l=e.height||1;t&&i&&r&&o&&a&&(n.yUp&&(r=Bh(r),o=Bh(o),a=Bh(a)),new $n(s,{src:i,type:t,pos:r,normal:o,up:a,clippable:!1,collidable:!0,height:l}))})),l&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!1}))}))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.visible=!0}))})));var p=e.components.visibility.view_setup_hints;p&&(!1===p.spaces_visible&&s.setObjectsVisible(r.metaScene.getObjectIDsByType("IfcSpace"),!1),void 0!==p.spaces_translucent&&s.setObjectsXRayed(r.metaScene.getObjectIDsByType("IfcSpace"),!0),p.space_boundaries_visible,!1===p.openings_visible&&s.setObjectsVisible(r.metaScene.getObjectIDsByType("IfcOpening"),!0),p.space_boundaries_translucent,void 0!==p.openings_translucent&&s.setObjectsXRayed(r.metaScene.getObjectIDsByType("IfcOpening"),!0))}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.selected=!0}))}))),e.components.translucency&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),e.components.translucency.forEach((function(e){return t._withBCFComponent(i,e,(function(e){return e.xrayed=!0}))}))),e.components.coloring&&e.components.coloring.forEach((function(e){var r=e.color,s=0,n=!1;8===r.length&&((s=parseInt(r.substring(0,2),16)/256)<=1&&s>=.95&&(s=1),r=r.substring(2),n=!0);var o=[parseInt(r.substring(0,2),16)/256,parseInt(r.substring(2,4),16)/256,parseInt(r.substring(4,6),16)/256];e.components.map((function(e){return t._withBCFComponent(i,e,(function(e){e.colorize=o,n&&(e.opacity=s)}))}))}))}if(e.perspective_camera||e.orthogonal_camera){var f,v,g,m;if(e.perspective_camera?(f=bh(e.perspective_camera.camera_view_point,fh),v=bh(e.perspective_camera.camera_direction,fh),g=bh(e.perspective_camera.camera_up_vector,fh),n.perspective.fov=e.perspective_camera.field_of_view,m="perspective"):(f=bh(e.orthogonal_camera.camera_view_point,fh),v=bh(e.orthogonal_camera.camera_direction,fh),g=bh(e.orthogonal_camera.camera_up_vector,fh),n.ortho.scale=e.orthogonal_camera.view_to_world_scale,m="ortho"),$.subVec3(f,u),n.yUp&&(f=Bh(f),v=Bh(v),g=Bh(g)),o){var _=s.pick({pickSurface:!0,origin:f,direction:v});v=_?_.worldPos:$.addVec3(f,v,fh)}else v=$.addVec3(f,v,fh);a?(n.eye=f,n.look=v,n.up=g,n.projection=m):r.cameraFlight.flyTo({eye:f,look:v,up:g,duration:i.duration,projection:m})}}}},{key:"_withBCFComponent",value:function(e,t,i){var r=this.viewer,s=r.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){var n=t.authoring_tool_id,o=s.objects[n];if(o)return void i(o);if(e.updateCompositeObjects)if(r.metaScene.metaObjects[n])return void s.withObjects(r.metaScene.getObjectIDsInSubtree(n),i)}if(t.ifc_guid){var a=t.ifc_guid,l=s.objects[a];if(l)return void i(l);if(e.updateCompositeObjects)if(r.metaScene.metaObjects[a])return void s.withObjects(r.metaScene.getObjectIDsInSubtree(a),i);Object.keys(s.models).forEach((function(t){var n=$.globalizeObjectId(t,a),o=s.objects[n];o?i(o):e.updateCompositeObjects&&r.metaScene.metaObjects[n]&&s.withObjects(r.metaScene.getObjectIDsInSubtree(n),i)}))}}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}();function yh(e){return{x:e[0],y:e[1],z:e[2]}}function bh(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function wh(e){return new Float64Array([e[0],-e[2],e[1]])}function Bh(e){return new Float64Array([e[0],e[2],-e[1]])}function xh(e){var t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0")}var Ph=$.vec3(),Ch=function(e,t,i,r){var s=e-i,n=t-r;return Math.sqrt(s*s+n*n)};var Mh=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,e.viewer.scene,s)).plugin=e,r._container=s.container,!r._container)throw"config missing: container";r._eventSubs={};var n=r.plugin.viewer.scene;r._originMarker=new et(n,s.origin),r._targetMarker=new et(n,s.target),r._originWorld=$.vec3(),r._targetWorld=$.vec3(),r._wp=new Float64Array(24),r._vp=new Float64Array(24),r._pp=new Float64Array(24),r._cp=new Float64Array(8),r._xAxisLabelCulled=!1,r._yAxisLabelCulled=!1,r._zAxisLabelCulled=!1,r._color=s.color||r.plugin.defaultColor;var o=s.onMouseOver?function(e){s.onMouseOver(e,b(r)),r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseover",e))}:null,a=s.onMouseLeave?function(e){s.onMouseLeave(e,b(r)),r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseleave",e))}:null,l=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousedown",e))},u=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mouseup",e))},A=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new MouseEvent("mousemove",e))},c=s.onContextMenu?function(e){s.onContextMenu(e,b(r))}:null,h=function(e){r.plugin.viewer.scene.canvas.canvas.dispatchEvent(new WheelEvent("wheel",e))};return r._originDot=new rt(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._targetDot=new rt(r._container,{fillColor:r._color,zIndex:void 0!==e.zIndex?e.zIndex+2:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._lengthWire=new it(r._container,{color:r._color,thickness:2,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._xAxisWire=new it(r._container,{color:"#FF0000",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._yAxisWire=new it(r._container,{color:"green",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._zAxisWire=new it(r._container,{color:"blue",thickness:1,thicknessClickable:6,zIndex:void 0!==e.zIndex?e.zIndex+1:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._lengthLabel=new st(r._container,{fillColor:r._color,prefix:"",text:"",zIndex:void 0!==e.zIndex?e.zIndex+4:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._xAxisLabel=new st(r._container,{fillColor:"red",prefix:"X",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._yAxisLabel=new st(r._container,{fillColor:"green",prefix:"Y",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._zAxisLabel=new st(r._container,{fillColor:"blue",prefix:"Z",text:"",zIndex:void 0!==e.zIndex?e.zIndex+3:void 0,onMouseOver:o,onMouseLeave:a,onMouseWheel:h,onMouseDown:l,onMouseUp:u,onMouseMove:A,onContextMenu:c}),r._measurementOrientation="Horizontal",r._wpDirty=!1,r._vpDirty=!1,r._cpDirty=!1,r._sectionPlanesDirty=!0,r._visible=!1,r._originVisible=!1,r._targetVisible=!1,r._wireVisible=!1,r._axisVisible=!1,r._xAxisVisible=!1,r._yAxisVisible=!1,r._zAxisVisible=!1,r._axisEnabled=!0,r._xLabelEnabled=!1,r._yLabelEnabled=!1,r._zLabelEnabled=!1,r._lengthLabelEnabled=!1,r._labelsVisible=!1,r._labelsOnWires=!1,r._clickable=!1,r._originMarker.on("worldPos",(function(e){r._originWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._targetMarker.on("worldPos",(function(e){r._targetWorld.set(e||[0,0,0]),r._wpDirty=!0,r._needUpdate(0)})),r._onViewMatrix=n.camera.on("viewMatrix",(function(){r._vpDirty=!0,r._needUpdate(0)})),r._onProjMatrix=n.camera.on("projMatrix",(function(){r._cpDirty=!0,r._needUpdate()})),r._onCanvasBoundary=n.canvas.on("boundary",(function(){r._cpDirty=!0,r._needUpdate(0)})),r._onMetricsUnits=n.metrics.on("units",(function(){r._cpDirty=!0,r._needUpdate()})),r._onMetricsScale=n.metrics.on("scale",(function(){r._cpDirty=!0,r._needUpdate()})),r._onMetricsOrigin=n.metrics.on("origin",(function(){r._cpDirty=!0,r._needUpdate()})),r._onSectionPlaneUpdated=n.on("sectionPlaneUpdated",(function(){r._sectionPlanesDirty=!0,r._needUpdate()})),r.approximate=s.approximate,r.visible=s.visible,r.originVisible=s.originVisible,r.targetVisible=s.targetVisible,r.wireVisible=s.wireVisible,r.axisVisible=s.axisVisible,r.xAxisVisible=s.xAxisVisible,r.yAxisVisible=s.yAxisVisible,r.zAxisVisible=s.zAxisVisible,r.xLabelEnabled=s.xLabelEnabled,r.yLabelEnabled=s.yLabelEnabled,r.zLabelEnabled=s.zLabelEnabled,r.lengthLabelEnabled=s.lengthLabelEnabled,r.labelsVisible=s.labelsVisible,r.labelsOnWires=s.labelsOnWires,r.useRotationAdjustment=s.useRotationAdjustment,r}return C(i,[{key:"_update",value:function(){if(this._visible){var e=this.plugin.viewer.scene;if(this._wpDirty&&(this._measurementOrientation=function(e,t,i){return Math.abs(t[1]-e[1])>i?"Vertical":"Horizontal"}(this._originWorld,this._targetWorld,0),"Vertical"===this._measurementOrientation&&this.useRotationAdjustment?(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._originWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._originWorld[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._wp[0]=this._originWorld[0],this._wp[1]=this._originWorld[1],this._wp[2]=this._originWorld[2],this._wp[3]=1,this._wp[4]=this._targetWorld[0],this._wp[5]=this._originWorld[1],this._wp[6]=this._originWorld[2],this._wp[7]=1,this._wp[8]=this._targetWorld[0],this._wp[9]=this._targetWorld[1],this._wp[10]=this._originWorld[2],this._wp[11]=1,this._wp[12]=this._targetWorld[0],this._wp[13]=this._targetWorld[1],this._wp[14]=this._targetWorld[2],this._wp[15]=1),this._wpDirty=!1,this._vpDirty=!0),this._vpDirty&&($.transformPositions4(e.camera.viewMatrix,this._wp,this._vp),this._vp[3]=1,this._vp[7]=1,this._vp[11]=1,this._vp[15]=1,this._vpDirty=!1,this._cpDirty=!0),this._sectionPlanesDirty){if(this._isSliced(this._originWorld)||this._isSliced(this._targetWorld))return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setCulled(!0),this._yAxisWire.setCulled(!0),this._zAxisWire.setCulled(!0),this._lengthWire.setCulled(!0),this._originDot.setCulled(!0),void this._targetDot.setCulled(!0);this._xAxisLabel.setCulled(!1),this._yAxisLabel.setCulled(!1),this._zAxisLabel.setCulled(!1),this._lengthLabel.setCulled(!1),this._xAxisWire.setCulled(!1),this._yAxisWire.setCulled(!1),this._zAxisWire.setCulled(!1),this._lengthWire.setCulled(!1),this._originDot.setCulled(!1),this._targetDot.setCulled(!1),this._sectionPlanesDirty=!0}var t=this._originMarker.viewPos[2],i=this._targetMarker.viewPos[2];if(t>-.3||i>-.3)return this._xAxisLabel.setCulled(!0),this._yAxisLabel.setCulled(!0),this._zAxisLabel.setCulled(!0),this._lengthLabel.setCulled(!0),this._xAxisWire.setVisible(!1),this._yAxisWire.setVisible(!1),this._zAxisWire.setVisible(!1),this._lengthWire.setVisible(!1),this._originDot.setVisible(!1),void this._targetDot.setVisible(!1);if(this._cpDirty){$.transformPositions4(e.camera.project.matrix,this._vp,this._pp);for(var r=this._pp,s=this._cp,n=e.canvas.canvas.getBoundingClientRect(),o=this._container.getBoundingClientRect(),a=n.top-o.top,l=n.left-o.left,u=e.canvas.boundary,A=u[2],c=u[3],h=0,d=this.plugin.viewer.scene.metrics,p=d.scale,f=d.units,v=d.unitsInfo[f].abbrev,g=0,m=r.length;g1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene))._canvasToPagePos=s.canvasToPagePos,r.pointerLens=s.pointerLens,r._active=!1,r._currentDistanceMeasurement=null,r._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},r._initMarkerDiv(),r._onCameraControlHoverSnapOrSurface=null,r._onCameraControlHoverSnapOrSurfaceOff=null,r._onMouseDown=null,r._onMouseUp=null,r._onCanvasTouchStart=null,r._onCanvasTouchEnd=null,r._snapping=!1!==s.snapping,r._mouseState=0,r._attachPlugin(e,s),r}return C(i,[{key:"_initMarkerDiv",value:function(){var e=document.createElement("div");e.setAttribute("id","myMarkerDiv");var t=this.scene.canvas.canvas;t.parentNode.insertBefore(e,t),e.style.background="black",e.style.border="2px solid blue",e.style.borderRadius="10px",e.style.width="5px",e.style.height="5px",e.style.top="-200px",e.style.left="-200px",e.style.margin="0 0",e.style.zIndex="100",e.style.position="absolute",e.style.pointerEvents="none",this._markerDiv=e}},{key:"_destroyMarkerDiv",value:function(){if(this._markerDiv){var e=document.getElementById("myMarkerDiv");e.parentNode.removeChild(e),this._markerDiv=null}}},{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){this._markerDiv||this._initMarkerDiv(),this.fire("activated",!0);var t=this.distanceMeasurementsPlugin,i=this.scene,r=t.viewer.cameraControl,s=i.canvas.canvas;i.input;var n,o,a=!1,l=$.vec3(),u=$.vec2(),A=null;this._mouseState=0;var c=function e(t){return t.offsetTop+(t.offsetParent&&t.offsetParent!==s.parentNode&&e(t.offsetParent))},h=function e(t){return t.offsetLeft+(t.offsetParent&&t.offsetParent!==s.parentNode&&e(t.offsetParent))},d=$.vec2();this._onCameraControlHoverSnapOrSurface=r.on(this._snapping?"hoverSnapOrSurface":"hoverSurface",(function(t){var i=t.snappedCanvasPos||t.canvasPos;a=!0,l.set(t.worldPos),u.set(t.canvasPos),0===e._mouseState?(e._canvasToPagePos?(e._canvasToPagePos(s,i,d),e._markerDiv.style.left="".concat(d[0]-5,"px"),e._markerDiv.style.top="".concat(d[1]-5,"px")):(e._markerDiv.style.left="".concat(h(s)+i[0]-5,"px"),e._markerDiv.style.top="".concat(c(s)+i[1]-5,"px")),e._markerDiv.style.background="pink",t.snappedToVertex||t.snappedToEdge?(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.snappedCanvasPos||t.canvasPos,e.pointerLens.snapped=!0),e._markerDiv.style.background="greenyellow",e._markerDiv.style.border="2px solid green"):(e.pointerLens&&(e.pointerLens.visible=!0,e.pointerLens.canvasPos=t.canvasPos,e.pointerLens.snappedCanvasPos=t.canvasPos,e.pointerLens.snapped=!1),e._markerDiv.style.background="pink",e._markerDiv.style.border="2px solid red"),A=t.entity):(e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px"),s.style.cursor="pointer",e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.wireVisible=e._currentDistanceMeasurementInitState.wireVisible,e._currentDistanceMeasurement.axisVisible=e._currentDistanceMeasurementInitState.axisVisible&&e.distanceMeasurementsPlugin.defaultAxisVisible,e._currentDistanceMeasurement.xAxisVisible=e._currentDistanceMeasurementInitState.xAxisVisible&&e.distanceMeasurementsPlugin.defaultXAxisVisible,e._currentDistanceMeasurement.yAxisVisible=e._currentDistanceMeasurementInitState.yAxisVisible&&e.distanceMeasurementsPlugin.defaultYAxisVisible,e._currentDistanceMeasurement.zAxisVisible=e._currentDistanceMeasurementInitState.zAxisVisible&&e.distanceMeasurementsPlugin.defaultZAxisVisible,e._currentDistanceMeasurement.targetVisible=e._currentDistanceMeasurementInitState.targetVisible,e._currentDistanceMeasurement.target.worldPos=l.slice(),e._markerDiv.style.left="-10000px",e._markerDiv.style.top="-10000px")})),s.addEventListener("mousedown",this._onMouseDown=function(e){1===e.which&&(n=e.clientX,o=e.clientY)}),s.addEventListener("mouseup",this._onMouseUp=function(i){1===i.which&&(i.clientX>n+20||i.clientXo+20||i.clientY1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"DistanceMeasurements",e))._pointerLens=s.pointerLens,r._container=s.container||document.body,r._defaultControl=null,r._measurements={},r.labelMinAxisLength=s.labelMinAxisLength,r.defaultVisible=!1!==s.defaultVisible,r.defaultOriginVisible=!1!==s.defaultOriginVisible,r.defaultTargetVisible=!1!==s.defaultTargetVisible,r.defaultWireVisible=!1!==s.defaultWireVisible,r.defaultXLabelEnabled=!1!==s.defaultXLabelEnabled,r.defaultYLabelEnabled=!1!==s.defaultYLabelEnabled,r.defaultZLabelEnabled=!1!==s.defaultZLabelEnabled,r.defaultLengthLabelEnabled=!1!==s.defaultLengthLabelEnabled,r.defaultLabelsVisible=!1!==s.defaultLabelsVisible,r.defaultAxisVisible=!1!==s.defaultAxisVisible,r.defaultXAxisVisible=!1!==s.defaultXAxisVisible,r.defaultYAxisVisible=!1!==s.defaultYAxisVisible,r.defaultZAxisVisible=!1!==s.defaultZAxisVisible,r.defaultColor=void 0!==s.defaultColor?s.defaultColor:"#00BBFF",r.zIndex=s.zIndex||1e4,r.defaultLabelsOnWires=!1!==s.defaultLabelsOnWires,r.useRotationAdjustment=void 0!==s.useRotationAdjustment&&!1!==s.useRotationAdjustment,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:b(r),distanceMeasurement:t,measurement:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:b(r),distanceMeasurement:t,measurement:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:b(r),distanceMeasurement:t,measurement:t,event:e})},r}return C(i,[{key:"getContainerElement",value:function(){return this._container}},{key:"send",value:function(e,t){}},{key:"pointerLens",get:function(){return this._pointerLens}},{key:"control",get:function(){return this._defaultControl||(this._defaultControl=new Fh(this,{})),this._defaultControl}},{key:"measurements",get:function(){return this._measurements}},{key:"labelMinAxisLength",get:function(){return this._labelMinAxisLength},set:function(e){e<1&&(this.error("labelMinAxisLength must be >= 1; defaulting to 25"),e=25),this._labelMinAxisLength=e||25}},{key:"useRotationAdjustment",get:function(){return this._useRotationAdjustment},set:function(e){e=void 0!==e&&Boolean(e),this._useRotationAdjustment=e}},{key:"createMeasurement",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=t.origin,r=t.target,s=new Mh(this,{id:t.id,plugin:this,container:this._container,origin:{entity:i.entity,worldPos:i.worldPos},target:{entity:r.entity,worldPos:r.worldPos},visible:t.visible,wireVisible:t.wireVisible,axisVisible:!1!==t.axisVisible&&!1!==this.defaultAxisVisible,xAxisVisible:!1!==t.xAxisVisible&&!1!==this.defaultXAxisVisible,yAxisVisible:!1!==t.yAxisVisible&&!1!==this.defaultYAxisVisible,zAxisVisibld:!1!==t.zAxisVisible&&!1!==this.defaultZAxisVisible,xLabelEnabled:!1!==t.xLabelEnabled&&!1!==this.defaultXLabelEnabled,yLabelEnabled:!1!==t.yLabelEnabled&&!1!==this.defaultYLabelEnabled,zLabelEnabled:!1!==t.zLabelEnabled&&!1!==this.defaultZLabelEnabled,lengthLabelEnabled:!1!==t.lengthLabelEnabled&&!1!==this.defaultLengthLabelEnabled,labelsVisible:!1!==t.labelsVisible&&!1!==this.defaultLabelsVisible,useRotationAdjustment:this.useRotationAdjustment,originVisible:t.originVisible,targetVisible:t.targetVisible,color:t.color,labelsOnWires:!1!==t.labelsOnWires&&!1!==this.defaultLabelsOnWires,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._measurements[s.id]=s,s.clickable=!0,s.on("destroyed",(function(){delete e._measurements[s.id]})),this.fire("measurementCreated",s),s}},{key:"destroyMeasurement",value:function(e){var t=this._measurements[e];t?(t.destroy(),this.fire("measurementDestroyed",t)):this.log("DistanceMeasurement not found: "+e)}},{key:"setLabelsShown",value:function(e){for(var t=0,i=Object.entries(this.measurements);t1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e.viewer.scene)).pointerLens=s.pointerLens,r.pointerCircle=new De(e.viewer),r._active=!1;var n=document.createElement("div"),o=r.scene.canvas.canvas;return o.parentNode.insertBefore(n,o),n.style.background="black",n.style.border="2px solid blue",n.style.borderRadius="10px",n.style.width="5px",n.style.height="5px",n.style.margin="-200px -200px",n.style.zIndex="100",n.style.position="absolute",n.style.pointerEvents="none",r.markerDiv=n,r._currentDistanceMeasurement=null,r._currentDistanceMeasurementInitState={wireVisible:null,axisVisible:null,xAxisVisible:null,yaxisVisible:null,zAxisVisible:null,targetVisible:null},r._onCanvasTouchStart=null,r._onCanvasTouchEnd=null,r._longTouchTimeoutMs=300,r._snapping=!1!==s.snapping,r._touchState=0,r._attachPlugin(e,s),r}return C(i,[{key:"_attachPlugin",value:function(e){this.distanceMeasurementsPlugin=e,this.plugin=e}},{key:"active",get:function(){return this._active}},{key:"snapping",get:function(){return this._snapping},set:function(e){e!==this._snapping?(this._snapping=e,this.deactivate(),this.activate()):this._snapping=e}},{key:"activate",value:function(){var e=this;if(!this._active){var t=this.plugin,i=this.scene,r=i.canvas.canvas;t.pointerLens;var s=$.vec3(),n=20,o=null;this._touchState=0;var a=$.vec2(),l=$.vec2(),u=$.vec2(),A=null,c=function(){e.plugin.viewer.cameraControl.active=!1},h=function(){e.plugin.viewer.cameraControl.active=!0};r.addEventListener("touchstart",this._onCanvasTouchStart=function(r){var u=r.touches.length;if(1===u){var d=r.touches[0],p=d.clientX,f=d.clientY;switch(a.set([p,f]),l.set([p,f]),e._touchState){case 0:if(1!==u&&null!==o)return o&&(clearTimeout(o),o=null),e._currentDistanceMeasurement&&(e._currentDistanceMeasurement.destroy(),e._currentDistanceMeasurement=null),h(),void(e._touchState=0);var v=i.pick({canvasPos:l,snapping:e._snapping,snapToEdge:e._snapping});if(v&&v.snapped)s.set(v.worldPos),e.pointerCircle.start(v.snappedCanvasPos);else{var g=i.pick({canvasPos:l,pickSurface:!0});if(!g||!g.worldPos)return;s.set(g.worldPos),e.pointerCircle.start(g.canvasPos)}o=setTimeout((function(){1!==u||l[0]>a[0]+n||l[0]a[1]+n||l[1]a[0]+n||l[0]a[1]+n||l[1]a[0]+n||da[1]+n||pa[0]+n||da[1]+n||p1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,"FastNav",e))._hideColorTexture=!1!==s.hideColorTexture,r._hidePBR=!1!==s.hidePBR,r._hideSAO=!1!==s.hideSAO,r._hideEdges=!1!==s.hideEdges,r._hideTransparentObjects=!!s.hideTransparentObjects,r._scaleCanvasResolution=!!s.scaleCanvasResolution,r._defaultScaleCanvasResolutionFactor=s.defaultScaleCanvasResolutionFactor||1,r._scaleCanvasResolutionFactor=s.scaleCanvasResolutionFactor||.6,r._delayBeforeRestore=!1!==s.delayBeforeRestore,r._delayBeforeRestoreSeconds=s.delayBeforeRestoreSeconds||.5;var n=1e3*r._delayBeforeRestoreSeconds,o=!1,a=function(){n=1e3*r._delayBeforeRestoreSeconds,o||(e.scene._renderer.setColorTextureEnabled(!r._hideColorTexture),e.scene._renderer.setPBREnabled(!r._hidePBR),e.scene._renderer.setSAOEnabled(!r._hideSAO),e.scene._renderer.setTransparentEnabled(!r._hideTransparentObjects),e.scene._renderer.setEdgesEnabled(!r._hideEdges),r._scaleCanvasResolution?e.scene.canvas.resolutionScale=r._scaleCanvasResolutionFactor:e.scene.canvas.resolutionScale=r._defaultScaleCanvasResolutionFactor,o=!0)},l=function(){e.scene.canvas.resolutionScale=r._defaultScaleCanvasResolutionFactor,e.scene._renderer.setEdgesEnabled(!0),e.scene._renderer.setColorTextureEnabled(!0),e.scene._renderer.setPBREnabled(!0),e.scene._renderer.setSAOEnabled(!0),e.scene._renderer.setTransparentEnabled(!0),o=!1};r._onCanvasBoundary=e.scene.canvas.on("boundary",a),r._onCameraMatrix=e.scene.camera.on("matrix",a),r._onSceneTick=e.scene.on("tick",(function(e){o&&(n-=e.deltaTime,(!r._delayBeforeRestore||n<=0)&&l())}));var u=!1;return r._onSceneMouseDown=e.scene.input.on("mousedown",(function(){u=!0})),r._onSceneMouseUp=e.scene.input.on("mouseup",(function(){u=!1})),r._onSceneMouseMove=e.scene.input.on("mousemove",(function(){u&&a()})),r}return C(i,[{key:"hideColorTexture",get:function(){return this._hideColorTexture},set:function(e){this._hideColorTexture=e}},{key:"hidePBR",get:function(){return this._hidePBR},set:function(e){this._hidePBR=e}},{key:"hideSAO",get:function(){return this._hideSAO},set:function(e){this._hideSAO=e}},{key:"hideEdges",get:function(){return this._hideEdges},set:function(e){this._hideEdges=e}},{key:"hideTransparentObjects",get:function(){return this._hideTransparentObjects},set:function(e){this._hideTransparentObjects=!1!==e}},{key:"scaleCanvasResolution",get:function(){return this._scaleCanvasResolution},set:function(e){this._scaleCanvasResolution=e}},{key:"defaultScaleCanvasResolutionFactor",get:function(){return this._defaultScaleCanvasResolutionFactor},set:function(e){this._defaultScaleCanvasResolutionFactor=e||1}},{key:"scaleCanvasResolutionFactor",get:function(){return this._scaleCanvasResolutionFactor},set:function(e){this._scaleCanvasResolutionFactor=e||.6}},{key:"delayBeforeRestore",get:function(){return this._delayBeforeRestore},set:function(e){this._delayBeforeRestore=e}},{key:"delayBeforeRestoreSeconds",get:function(){return this._delayBeforeRestoreSeconds},set:function(e){this._delayBeforeRestoreSeconds=null!=e?e:.5}},{key:"send",value:function(e,t){}},{key:"destroy",value:function(){this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),Sh=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getMetaModel",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLTF",value:function(e,t,i){le.loadArraybuffer(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getGLB",value:function(e,t,i){le.loadArraybuffer(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getArrayBuffer",value:function(e,t,i,r){!function(e,t,i,r){var s=function(){};i=i||s,r=r||s;var n=/^data:(.*?)(;base64)?,(.*)$/,o=t.match(n);if(o){var a=!!o[2],l=o[3];l=window.decodeURIComponent(l),a&&(l=window.atob(l));try{for(var u=new ArrayBuffer(l.length),A=new Uint8Array(u),c=0;c0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=t.messages,this.locale=t.locale}return C(e,[{key:"messages",set:function(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}},{key:"loadMessages",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in e)this._messages[t]=e[t];this.messages=this._messages}},{key:"clearMessages",value:function(){this.messages={}}},{key:"locales",get:function(){return this._locales}},{key:"locale",get:function(){return this._locale},set:function(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}},{key:"translate",value:function(e,t){var i=this._messages[this._locale];if(!i)return null;var r=Lh(e,i);return r?t?Rh(r,t):r:null}},{key:"translatePlurals",value:function(e,t,i){var r=this._messages[this._locale];if(!r)return null;var s=Lh(e,r);return(s=0===(t=parseInt(""+t,10))?s.zero:t>1?s.other:s.one)?(s=Rh(s,[t]),i&&(s=Rh(s,i)),s):null}},{key:"fire",value:function(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);var r=this._eventSubs[e];if(r)for(var s in r){if(r.hasOwnProperty(s))r[s].callback(t)}}},{key:"on",value:function(e,t){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new Q),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});var i=this._eventSubs[e];i||(i={},this._eventSubs[e]=i);var r=this._eventSubIDMap.addItem();i[r]={callback:t},this._eventSubEvents[r]=e;var s=this._events[e];return void 0!==s&&t(s),r}},{key:"off",value:function(e){if(null!=e&&this._eventSubEvents){var t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];var i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}}]),e}();function Lh(e,t){if(t[e])return t[e];for(var i=e.split("."),r=t,s=0,n=i.length;r&&s1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}var Uh=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).t=s.t,r}return C(i,[{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"tangent",get:function(){return this.getTangent(this._t)}},{key:"length",get:function(){var e=this._getLengths();return e[e.length-1]}},{key:"getTangent",value:function(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,r=e+t;i<0&&(i=0),r>1&&(r=1);var s=this.getPoint(i),n=this.getPoint(r),o=$.subVec3(n,s,[]);return $.normalizeVec3(o,[])}},{key:"getPointAt",value:function(e){var t=this.getUToTMapping(e);return this.getPoint(t)}},{key:"getPoints",value:function(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}},{key:"_getLengths",value:function(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,r=[],s=this.getPoint(0),n=0;for(r.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=$.lenVec3($.subVec3(t,s,[])),r.push(n),s=t;return this.cacheArcLengths=r,r}},{key:"_updateArcLengths",value:function(){this.needsUpdate=!0,this._getLengths()}},{key:"getUToTMapping",value:function(e,t){var i,r=this._getLengths(),s=0,n=r.length;i=t||e*r[n-1];for(var o,a=0,l=n-1;a<=l;)if((o=r[s=Math.floor(a+(l-a)/2)]-i)<0)a=s+1;else{if(!(o>0)){l=s;break}l=s-1}if(r[s=l]===i)return s/(n-1);var u=r[s];return(s+(i-u)/(r[s+1]-u))/(n-1)}}]),i}(),Oh=function(e){g(i,Uh);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).points=s.points,r.t=s.t,r}return C(i,[{key:"points",get:function(){return this._points},set:function(e){this._points=e||[]}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,r=Math.floor(i),s=i-r,n=t[0===r?r:r-1],o=t[r],a=t[r>t.length-2?t.length-1:r+1],l=t[r>t.length-3?t.length-1:r+2],u=$.vec3();return u[0]=$.catmullRomInterpolate(n[0],o[0],a[0],l[0],s),u[1]=$.catmullRomInterpolate(n[1],o[1],a[1],l[1],s),u[2]=$.catmullRomInterpolate(n[2],o[2],a[2],l[2],s),u}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}},{key:"getJSON",value:function(){return{points:points,t:this._t}}}]),i}(),Nh=$.vec3(),Qh=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._frames=[],r._eyeCurve=new Oh(b(r)),r._lookCurve=new Oh(b(r)),r._upCurve=new Oh(b(r)),s.frames&&(r.addFrames(s.frames),r.smoothFrameTimes(1)),r}return C(i,[{key:"type",get:function(){return"CameraPath"}},{key:"frames",get:function(){return this._frames}},{key:"eyeCurve",get:function(){return this._eyeCurve}},{key:"lookCurve",get:function(){return this._lookCurve}},{key:"upCurve",get:function(){return this._upCurve}},{key:"saveFrame",value:function(e){var t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}},{key:"addFrame",value:function(e,t,i,r){var s={t:e,eye:t.slice(0),look:i.slice(0),up:r.slice(0)};this._frames.push(s),this._eyeCurve.points.push(s.eye),this._lookCurve.points.push(s.look),this._upCurve.points.push(s.up)}},{key:"addFrames",value:function(e){for(var t,i=0,r=e.length;i1?1:e,t.eye=this._eyeCurve.getPoint(e,Nh),t.look=this._lookCurve.getPoint(e,Nh),t.up=this._upCurve.getPoint(e,Nh)}},{key:"sampleFrame",value:function(e,t,i,r){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,r)}},{key:"smoothFrameTimes",value:function(e){if(0!==this._frames.length){var t=$.vec3(),i=0;this._frames[0].t=0;for(var r=[],s=1,n=this._frames.length;s1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._look1=$.vec3(),r._eye1=$.vec3(),r._up1=$.vec3(),r._look2=$.vec3(),r._eye2=$.vec3(),r._up2=$.vec3(),r._orthoScale1=1,r._orthoScale2=1,r._flying=!1,r._flyEyeLookUp=!1,r._flyingEye=!1,r._flyingLook=!1,r._callback=null,r._callbackScope=null,r._time1=null,r._time2=null,r.easing=!1!==s.easing,r.duration=s.duration,r.fit=s.fit,r.fitFOV=s.fitFOV,r.trail=s.trail,r}return C(i,[{key:"type",get:function(){return"CameraFlightAnimation"}},{key:"flyTo",value:function(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;var r,s,n,o,a,l=this.scene.camera,u=!!e.projection&&e.projection!==l.projection;if(this._eye1[0]=l.eye[0],this._eye1[1]=l.eye[1],this._eye1[2]=l.eye[2],this._look1[0]=l.look[0],this._look1[1]=l.look[1],this._look1[2]=l.look[2],this._up1[0]=l.up[0],this._up1[1]=l.up[1],this._up1[2]=l.up[2],this._orthoScale1=l.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)r=e.aabb;else if(6===e.length)r=e;else if(e.eye&&e.look||e.up)s=e.eye,n=e.look,o=e.up;else if(e.eye)s=e.eye;else if(e.look)n=e.look;else{var A=e;if((le.isNumeric(A)||le.isString(A))&&(a=A,!(A=this.scene.components[a])))return this.error("Component not found: "+le.inQuotes(a)),void(t&&(i?t.call(i):t()));u||(r=A.aabb||this.scene.aabb)}var c=e.poi;if(r){if(r[3]=1;e>1&&(e=1);var r=this.easing?i._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?($.subVec3(s.eye,s.look,zh),s.eye=$.lerpVec3(r,0,1,this._eye1,this._eye2,jh),s.look=$.subVec3(jh,zh,Hh)):this._flyingLook&&(s.look=$.lerpVec3(r,0,1,this._look1,this._look2,Hh),s.up=$.lerpVec3(r,0,1,this._up1,this._up2,Gh)):this._flyingEyeLookUp&&(s.eye=$.lerpVec3(r,0,1,this._eye1,this._eye2,jh),s.look=$.lerpVec3(r,0,1,this._look1,this._look2,Hh),s.up=$.lerpVec3(r,0,1,this._up1,this._up2,Gh)),this._projection2){var n="ortho"===this._projection2?i._easeOutExpo(e,0,1,1):i._easeInCubic(e,0,1,1);s.customProjection.matrix=$.lerpMat4(n,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();_e.scheduleTask(this._update,this)}}},{key:"stop",value:function(){if(this._flying){this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);var e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}}},{key:"cancel",value:function(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}},{key:"duration",get:function(){return this._duration/1e3},set:function(e){this._duration=e?1e3*e:500,this.stop()}},{key:"fit",get:function(){return this._fit},set:function(e){this._fit=!1!==e}},{key:"fitFOV",get:function(){return this._fitFOV},set:function(e){this._fitFOV=e||45}},{key:"trail",get:function(){return this._trail},set:function(e){this._trail=!!e}},{key:"destroy",value:function(){this.stop(),f(w(i.prototype),"destroy",this).call(this)}}],[{key:"_ease",value:function(e,t,i,r){return-i*(e/=r)*(e-2)+t}},{key:"_easeInCubic",value:function(e,t,i,r){return i*(e/=r)*e*e+t}},{key:"_easeOutExpo",value:function(e,t,i,r){return i*(1-Math.pow(2,-10*e/r))+t}}]),i}(),Kh=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._cameraFlightAnimation=new Wh(b(r)),r._t=0,r.state=i.SCRUBBING,r._playingFromT=0,r._playingToT=0,r._playingRate=s.playingRate||1,r._playingDir=1,r._lastTime=null,r.cameraPath=s.cameraPath,r._tick=r.scene.on("tick",r._updateT,b(r)),r}return C(i,[{key:"type",get:function(){return"CameraPathAnimation"}},{key:"_updateT",value:function(){var e=this._cameraPath;if(e){var t,r,s=performance.now(),n=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==n)switch(this.state){case i.SCRUBBING:return;case i.PLAYING:if(this._t+=this._playingRate*n,0===(t=this._cameraPath.frames.length)||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=i.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case i.PLAYING_TO:r=this._t+this._playingRate*n*this._playingDir,(this._playingDir<0&&r<=this._playingToT||this._playingDir>0&&r>=this._playingToT)&&(r=this._playingToT,this.state=i.SCRUBBING,this.fire("stopped")),this._t=r,e.loadFrame(this._t)}}}},{key:"_ease",value:function(e,t,i,r){return-i*(e/=r)*(e-2)+t}},{key:"cameraPath",get:function(){return this._cameraPath},set:function(e){this._cameraPath=e}},{key:"rate",get:function(){return this._playingRate},set:function(e){this._playingRate=e}},{key:"play",value:function(){this._cameraPath&&(this._lastTime=null,this.state=i.PLAYING)}},{key:"playToT",value:function(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=i.PLAYING_TO)}},{key:"playToFrame",value:function(e){var t=this._cameraPath;if(t){var i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}}},{key:"flyToFrame",value:function(e,t){var r=this._cameraPath;if(r){var s=r.frames[e];s?(this.state=i.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}}},{key:"scrubToT",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=i.SCRUBBING))}},{key:"scrubToFrame",value:function(e){var t=this._cameraPath;t&&(this.scene.camera&&(t.frames[e]?(t.loadFrame(this._t),this.state=i.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)))}},{key:"stop",value:function(){this.state=i.SCRUBBING,this.fire("stopped")}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene.off(this._tick)}}]),i}();Kh.STOPPED=0,Kh.SCRUBBING=1,Kh.PLAYING=2,Kh.PLAYING_TO=3;var Xh=$.vec3(),Yh=$.vec3();$.vec3();var Jh=$.vec3([0,-1,0]),Zh=$.vec4([0,0,0,1]),qh=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._src=null,r._image=null,r._pos=$.vec3(),r._origin=$.vec3(),r._rtcPos=$.vec3(),r._dir=$.vec3(),r._size=1,r._imageSize=$.vec2(),r._texture=new On(b(r)),r._plane=new nn(b(r),{geometry:new Ti(b(r),Yn({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Ni(b(r),{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:r._texture,emissiveMap:r._texture,backfaces:!0}),clippable:s.clippable}),r._grid=new nn(b(r),{geometry:new Ti(b(r),Xn({size:1,divisions:10})),material:new Ni(b(r),{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:s.clippable}),r._node=new wn(b(r),{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[r._plane,r._grid]}),r._gridVisible=!1,r.visible=!0,r.gridVisible=s.gridVisible,r.position=s.position,r.rotation=s.rotation,r.dir=s.dir,r.size=s.size,r.collidable=s.collidable,r.clippable=s.clippable,r.pickable=s.pickable,r.opacity=s.opacity,s.image?r.image=s.image:r.src=s.src,r}return C(i,[{key:"visible",get:function(){return this._plane.visible},set:function(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}},{key:"gridVisible",get:function(){return this._gridVisible},set:function(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"position",get:function(){return this._pos},set:function(e){this._pos.set(e||[0,0,0]),Re(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}},{key:"rotation",get:function(){return this._node.rotation},set:function(e){this._node.rotation=e}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"dir",get:function(){return this._dir},set:function(e){if(this._dir.set(e||[0,0,-1]),e){var t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];$.subVec3(t,this.position,Xh);var r=-$.dotVec3(i,Xh);$.normalizeVec3(i),$.mulVec3Scalar(i,r,Yh),$.vec3PairToQuaternion(Jh,e,Zh),this._node.quaternion=Zh}}},{key:"collidable",get:function(){return this._node.collidable},set:function(e){this._node.collidable=!1!==e}},{key:"clippable",get:function(){return this._node.clippable},set:function(e){this._node.clippable=!1!==e}},{key:"pickable",get:function(){return this._node.pickable},set:function(e){this._node.pickable=!1!==e}},{key:"opacity",get:function(){return this._node.opacity},set:function(e){this._node.opacity=e}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}},{key:"_updatePlaneSizeFromImage",value:function(){var e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){var r=i/t;this._node.scale=[e,1,e*r]}else{var s=t/i;this._node.scale=[e*s,1,e]}}}]),i}(),$h=function(e){g(i,yi);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i);var n=b(r=t.call(this,e,s));r._shadowRenderBuf=null,r._shadowViewMatrix=null,r._shadowProjMatrix=null,r._shadowViewMatrixDirty=!0,r._shadowProjMatrixDirty=!0;var o=r.scene.camera,a=r.scene.canvas;return r._onCameraViewMatrix=o.on("viewMatrix",(function(){r._shadowViewMatrixDirty=!0})),r._onCameraProjMatrix=o.on("projMatrix",(function(){r._shadowProjMatrixDirty=!0})),r._onCanvasBoundary=a.on("boundary",(function(){r._shadowProjMatrixDirty=!0})),r._state=new qt({type:"point",pos:$.vec3([1,1,1]),color:$.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:s.space||"view",castsShadow:!1,getShadowViewMatrix:function(){if(n._shadowViewMatrixDirty){n._shadowViewMatrix||(n._shadowViewMatrix=$.identityMat4());var e=n._state.pos,t=o.look,i=o.up;$.lookAtMat4v(e,t,i,n._shadowViewMatrix),n._shadowViewMatrixDirty=!1}return n._shadowViewMatrix},getShadowProjMatrix:function(){if(n._shadowProjMatrixDirty){n._shadowProjMatrix||(n._shadowProjMatrix=$.identityMat4());var e=n.scene.canvas.canvas;$.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,n._shadowProjMatrix),n._shadowProjMatrixDirty=!1}return n._shadowProjMatrix},getShadowRenderBuf:function(){return n._shadowRenderBuf||(n._shadowRenderBuf=new Wt(n.scene.canvas.canvas,n.scene.canvas.gl,{size:[1024,1024]})),n._shadowRenderBuf}}),r.pos=s.pos,r.color=s.color,r.intensity=s.intensity,r.constantAttenuation=s.constantAttenuation,r.linearAttenuation=s.linearAttenuation,r.quadraticAttenuation=s.quadraticAttenuation,r.castsShadow=s.castsShadow,r.scene._lightCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"PointLight"}},{key:"pos",get:function(){return this._state.pos},set:function(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}},{key:"color",get:function(){return this._state.color},set:function(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}},{key:"intensity",get:function(){return this._state.intensity},set:function(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}},{key:"constantAttenuation",get:function(){return this._state.attenuation[0]},set:function(e){this._state.attenuation[0]=e||0,this.glRedraw()}},{key:"linearAttenuation",get:function(){return this._state.attenuation[1]},set:function(e){this._state.attenuation[1]=e||0,this.glRedraw()}},{key:"quadraticAttenuation",get:function(){return this._state.attenuation[2]},set:function(e){this._state.attenuation[2]=e||0,this.glRedraw()}},{key:"castsShadow",get:function(){return this._state.castsShadow},set:function(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}},{key:"destroy",value:function(){var e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),f(w(i.prototype),"destroy",this).call(this),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}]),i}();function ed(e){return 0==(e&e-1)}function td(e){--e;for(var t=1;t<32;t<<=1)e|=e>>t;return e+1}var id=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i);var n=(r=t.call(this,e,s)).scene.canvas.gl;return r._state=new qt({texture:new Dn({gl:n,target:n.TEXTURE_CUBE_MAP}),flipY:r._checkFlipY(s.minFilter),encoding:r._checkEncoding(s.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),r._src=s.src,r._images=[],r._loadSrc(s.src),re.memory.textures++,r}return C(i,[{key:"type",get:function(){return"CubeTexture"}},{key:"_checkFlipY",value:function(e){return!!e}},{key:"_checkEncoding",value:function(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}},{key:"_webglContextRestored",value:function(){this.scene.canvas.gl,this._state.texture=null,this._src&&this._loadSrc(this._src)}},{key:"_loadSrc",value:function(e){var t=this,i=this.scene.canvas.gl;this._images=[];for(var r=!1,s=0,n=function(n){var o,a,l=new Image;l.onload=(o=l,a=n,function(){if(!r&&(o=function(e){if(!ed(e.width)||!ed(e.height)){var t=document.createElement("canvas");t.width=td(e.width),t.height=td(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}(o),t._images[a]=o,6==++s)){var e=t._state.texture;e||(e=new Dn({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}),l.onerror=function(){r=!0},l.src=e[n]},o=0;o1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).scene._lightsState.addReflectionMap(r._state),r.scene._reflectionMapCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"ReflectionMap"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._reflectionMapDestroyed(this)}}]),i}(),sd=function(e){g(i,id);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).scene._lightMapCreated(b(r)),r}return C(i,[{key:"type",get:function(){return"LightMap"}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this),this.scene._lightMapDestroyed(this)}}]),i}(),nd=function(e){g(i,et);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,{entity:s.entity,occludable:s.occludable,worldPos:s.worldPos}))._occluded=!1,r._visible=!0,r._src=null,r._image=null,r._pos=$.vec3(),r._origin=$.vec3(),r._rtcPos=$.vec3(),r._dir=$.vec3(),r._size=1,r._imageSize=$.vec2(),r._texture=new On(b(r),{src:s.src}),r._geometry=new Ti(b(r),{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]}),r._mesh=new nn(b(r),{geometry:r._geometry,material:new Ni(b(r),{ambient:[.9,.3,.9],shininess:30,diffuseMap:r._texture,backfaces:!0}),scale:[1,1,1],position:s.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),r.visible=!0,r.collidable=s.collidable,r.clippable=s.clippable,r.pickable=s.pickable,r.opacity=s.opacity,r.size=s.size,s.image?r.image=s.image:r.src=s.src,r}return C(i,[{key:"_setVisible",value:function(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,f(w(i.prototype),"_setVisible",this).call(this,e)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}},{key:"image",get:function(){return this._image},set:function(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}},{key:"src",get:function(){return this._src},set:function(e){var t=this;if(this._src=e,this._src){this._image=null;var i=new Image;i.onload=function(){t._texture.image=i,t._imageSize[0]=i.width,t._imageSize[1]=i.height,t._updatePlaneSizeFromImage()},i.src=this._src}}},{key:"size",get:function(){return this._size},set:function(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}},{key:"collidable",get:function(){return this._mesh.collidable},set:function(e){this._mesh.collidable=!1!==e}},{key:"clippable",get:function(){return this._mesh.clippable},set:function(e){this._mesh.clippable=!1!==e}},{key:"pickable",get:function(){return this._mesh.pickable},set:function(e){this._mesh.pickable=!1!==e}},{key:"opacity",get:function(){return this._mesh.opacity},set:function(e){this._mesh.opacity=e}},{key:"_updatePlaneSizeFromImage",value:function(){var e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],r=i/t;this._geometry.positions=t>i?[e,e*r,0,-e,e*r,0,-e,-e*r,0,e,-e*r,0]:[e/r,e,0,-e/r,e,0,-e/r,-e,0,e/r,-e,0]}}]),i}(),od=function(){function e(t){x(this,e),this._eye=$.vec3(),this._look=$.vec3(),this._up=$.vec3(),this._projection={},t&&this.saveCamera(t)}return C(e,[{key:"saveCamera",value:function(e){var t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}},{key:"restoreCamera",value:function(e,t){var i=e.camera,r=this._projection;function s(){switch(r.type){case"perspective":i.perspective.fov=r.fov,i.perspective.fovAxis=r.fovAxis,i.perspective.near=r.near,i.perspective.far=r.far;break;case"ortho":i.ortho.scale=r.scale,i.ortho.near=r.near,i.ortho.far=r.far;break;case"frustum":i.frustum.left=r.left,i.frustum.right=r.right,i.frustum.top=r.top,i.frustum.bottom=r.bottom,i.frustum.near=r.near,i.frustum.far=r.far;break;case"custom":i.customProjection.matrix=r.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:r.scale,projection:r.projection},(function(){s(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,s(),i.projection=r.projection)}}]),e}(),ad=$.vec3(),ld=function(){function e(t){if(x(this,e),this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,t){var i=t.metaScene.scene;this.saveObjects(i,t)}}return C(e,[{key:"saveObjects",value:function(e,t,i){this.numObjects=0,this._mask=i?le.apply(i,{}):null;for(var r=!i||i.visible,s=!i||i.edges,n=!i||i.xrayed,o=!i||i.highlighted,a=!i||i.selected,l=!i||i.clippable,u=!i||i.pickable,A=!i||i.colorize,c=!i||i.opacity,h=t.metaObjects,d=e.objects,p=0,f=h.length;p1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).v0=s.v0,r.v1=s.v1,r.v2=s.v2,r.v3=s.v3,r.t=s.t,r}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"v3",get:function(){return this._v3},set:function(e){this.fire("v3",this._v3=e||$.vec3([0,0,0]))}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=$.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=$.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}]),i}(),hd=function(e){g(i,Uh);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._cachedLengths=[],r._dirty=!0,r._curves=[],r._t=0,r._dirtySubs=[],r._destroyedSubs=[],r.curves=s.curves||[],r.t=s.t,r}return C(i,[{key:"addCurve",value:function(e){this._curves.push(e),this._dirty=!0}},{key:"curves",get:function(){return this._curves},set:function(e){var t,i,r;for(e=e||[],i=0,r=this._curves.length;i1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"length",get:function(){var e=this._getCurveLengths();return e[e.length-1]}},{key:"getPoint",value:function(e){for(var t,i=e*this.length,r=this._getCurveLengths(),s=0;s=i){var n=1-(r[s]-i)/(t=this._curves[s]).length;return t.getPointAt(n)}s++}return null}},{key:"_getCurveLengths",value:function(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,r=this._curves.length;for(e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s)).v0=s.v0,r.v1=s.v1,r.v2=s.v2,r.t=s.t,r}return C(i,[{key:"v0",get:function(){return this._v0},set:function(e){this._v0=e||$.vec3([0,0,0])}},{key:"v1",get:function(){return this._v1},set:function(e){this._v1=e||$.vec3([0,0,0])}},{key:"v2",get:function(){return this._v2},set:function(e){this._v2=e||$.vec3([0,0,0])}},{key:"t",get:function(){return this._t},set:function(e){e=e||0,this._t=e<0?0:e>1?1:e}},{key:"point",get:function(){return this.getPoint(this._t)}},{key:"getPoint",value:function(e){var t=$.vec3();return t[0]=$.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=$.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=$.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}},{key:"getJSON",value:function(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}]),i}(),pd=function(e){g(i,hh);var t=_(i);function i(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),t.call(this,e,r)}return C(i)}(),fd=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e,s))._skyboxMesh=new nn(b(r),{geometry:new Ti(b(r),{primitive:"triangles",positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),background:!0,scale:[2e3,2e3,2e3],rotation:[0,-90,0],material:new Ni(b(r),{ambient:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],emissive:[1,1,1],emissiveMap:new On(b(r),{src:s.src,flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge",encoding:s.encoding||"sRGB"}),backfaces:!0}),visible:!1,pickable:!1,clippable:!1,collidable:!1}),r.size=s.size,r.active=s.active,r}return C(i,[{key:"size",get:function(){return this._size},set:function(e){this._size=e||1e3,this._skyboxMesh.scale=[this._size,this._size,this._size]}},{key:"active",get:function(){return this._skyboxMesh.visible},set:function(e){this._skyboxMesh.visible=e}}]),i}(),vd=function(){function e(){x(this,e)}return C(e,[{key:"transcode",value:function(e,t){}},{key:"destroy",value:function(){}}]),e}(),gd=$.vec4(),md=$.vec4(),_d=$.vec3(),yd=$.vec3(),bd=$.vec3(),wd=$.vec4(),Bd=$.vec4(),xd=$.vec4(),Pd=function(){function e(t){x(this,e),this._scene=t}return C(e,[{key:"dollyToCanvasPos",value:function(e,t,i){var r=!1,s=this._scene.camera;if(e){var n=$.subVec3(e,s.eye,_d);r=$.lenVec3(n)0&&void 0!==arguments[0]?arguments[0]:{};this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);var t=e.color||[1,0,0];this._pivotSphereMaterial=new Ni(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}},{key:"disablePivotSphere",value:function(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}},{key:"startPivot",value:function(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;var e=this._scene.camera,t=$.lookAtMat4v(e.eye,e.look,e.worldUp);$.transformPoint3(t,this.getPivotPos(),this._cameraOffset);var i=this.getPivotPos();this._cameraOffset[2]+=$.distVec3(e.eye,i),t=$.inverseMat4(t);var r=$.transformVec3(t,this._cameraOffset),s=$.vec3();if($.subVec3(e.eye,i,s),$.addVec3(s,r),e.zUp){var n=s[1];s[1]=s[2],s[2]=n}this._radius=$.lenVec3(s),this._polar=Math.acos(s[1]/this._radius),this._azimuth=Math.atan2(s[0],s[2]),this._pivoting=!0}},{key:"_cameraLookingDownwards",value:function(){var e=this._scene.camera,t=$.normalizeVec3($.subVec3(e.look,e.eye,Cd)),i=$.cross3Vec3(t,e.worldUp,Md);return $.sqLenVec3(i)<=1e-4}},{key:"getPivoting",value:function(){return this._pivoting}},{key:"setPivotPos",value:function(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}},{key:"setCanvasPivotPos",value:function(e){var t=this._scene.camera,i=Math.abs($.distVec3(this._scene.center,t.eye)),r=t.project.transposedMatrix,s=r.subarray(8,12),n=r.subarray(12),o=[0,0,-1,1],a=$.dotVec4(o,s)/$.dotVec4(o,n),l=Fd;t.project.unproject(e,a,kd,Id,l);var u=$.normalizeVec3($.subVec3(l,t.eye,Cd)),A=$.addVec3(t.eye,$.mulVec3Scalar(u,i,Md),Ed);this.setPivotPos(A)}},{key:"getPivotPos",value:function(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}},{key:"continuePivot",value:function(e,t){if(this._pivoting&&(0!==e||0!==t)){var i=this._scene.camera,r=-e,s=-t;1===i.worldUp[2]&&(r=-r),this._azimuth+=.01*-r,this._polar+=.01*s,this._polar=$.clamp(this._polar,.001,Math.PI-.001);var n=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){var o=n[1];n[1]=n[2],n[2]=o}var a=$.lenVec3($.subVec3(i.look,i.eye,$.vec3())),l=this.getPivotPos();$.addVec3(n,l);var u=$.lookAtMat4v(n,l,i.worldUp);u=$.inverseMat4(u);var A=$.transformVec3(u,this._cameraOffset);u[12]-=A[0],u[13]-=A[1],u[14]-=A[2];var c=[u[8],u[9],u[10]];i.eye=[u[12],u[13],u[14]],$.subVec3(i.eye,$.mulVec3Scalar(c,a),i.look),i.up=[u[4],u[5],u[6]],this.showPivot()}}},{key:"showPivot",value:function(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}},{key:"hidePivot",value:function(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}},{key:"endPivot",value:function(){this._pivoting=!1}},{key:"destroy",value:function(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}]),e}(),Sd=function(){function e(t,i){x(this,e),this._scene=t.scene,this._cameraControl=t,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=i,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=$.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}return C(e,[{key:"update",value:function(){if(this._configs.pointerEnabled&&(this.schedulePickEntity||this.schedulePickSurface)){var e="".concat(~~this.pickCursorPos[0],"-").concat(~~this.pickCursorPos[1],"-").concat(this.scheduleSnapOrPick,"-").concat(this.schedulePickSurface,"-").concat(this.schedulePickEntity);if(this._lastHash!==e){this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;var t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){var i=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});i&&(i.snappedToEdge||i.snappedToVertex)?(this.snapPickResult=i,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){var r=this.pickResult.canvasPos;if(r[0]===this.pickCursorPos[0]&&r[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){var s=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(s[0]===this.pickCursorPos[0]&&s[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}}}},{key:"fireEvents",value:function(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){var e=new xt;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){var t=this.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=t)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}]),e}(),Td=$.vec2(),Ld=function(){function e(t,i,r,s,n){x(this,e),this._scene=t;var o,a,l,u=i.pickController,A=0,c=0,h=0,d=0,p=!1,f=$.vec3(),v=!0,g=this._scene.canvas.canvas,m=[];function _(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];g.style.cursor="move",y(),e&&b()}function y(){A=s.pointerCanvasPos[0],c=s.pointerCanvasPos[1],h=s.pointerCanvasPos[0],d=s.pointerCanvasPos[1]}function b(){u.pickCursorPos=s.pointerCanvasPos,u.schedulePickSurface=!0,u.update(),u.picked&&u.pickedSurface&&u.pickResult&&u.pickResult.worldPos?(p=!0,f.set(u.pickResult.worldPos)):p=!1}document.addEventListener("keydown",this._documentKeyDownHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!0}}),document.addEventListener("keyup",this._documentKeyUpHandler=function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled){var i=e.keyCode;m[i]=!1}}),g.addEventListener("mousedown",this._mouseDownHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:m[t.input.KEY_SHIFT]||r.planView?(o=!0,_()):(o=!0,_(!1));break;case 2:a=!0,_();break;case 3:l=!0,r.panRightClick&&_()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&(o||a||l)){var i=t.canvas.boundary,u=i[2],h=i[3],d=s.pointerCanvasPos[0],v=s.pointerCanvasPos[1],g=m[t.input.KEY_SHIFT]||r.planView||!r.panRightClick&&a||r.panRightClick&&l,_=document.pointerLockElement?e.movementX:d-A,y=document.pointerLockElement?e.movementY:v-c;if(g){var b=t.camera;if("perspective"===b.projection){var w=Math.abs(p?$.lenVec3($.subVec3(f,t.camera.eye,[])):t.camera.eyeLookDist)*Math.tan(b.perspective.fov/2*Math.PI/180);n.panDeltaX+=1.5*_*w/h,n.panDeltaY+=1.5*y*w/h}else n.panDeltaX+=.5*b.ortho.scale*(_/h),n.panDeltaY+=.5*b.ortho.scale*(y/h)}else!o||a||l||r.planView||(r.firstPerson?(n.rotateDeltaY-=_/u*r.dragRotationRate/2,n.rotateDeltaX+=y/h*(r.dragRotationRate/4)):(n.rotateDeltaY-=_/u*(1.5*r.dragRotationRate),n.rotateDeltaX+=y/h*(1.5*r.dragRotationRate)));A=d,c=v}}),g.addEventListener("mousemove",this._canvasMouseMoveHandler=function(e){r.active&&r.pointerEnabled&&s.mouseover&&(v=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){if(r.active&&r.pointerEnabled)switch(e.which){case 1:case 2:case 3:o=!1,a=!1,l=!1}}),g.addEventListener("mouseup",this._mouseUpHandler=function(e){if(r.active&&r.pointerEnabled){if(3===e.which){!function(e,t){if(e){for(var i=e.target,r=0,s=0,n=0,o=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,n+=i.scrollLeft,o+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-r,t[1]=e.pageY+o-s}else e=window.event,t[0]=e.x,t[1]=e.y}(e,Td);var t=Td[0],s=Td[1];Math.abs(t-h)<3&&Math.abs(s-d)<3&&i.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:Td,event:e},!0)}g.style.removeProperty("cursor")}}),g.addEventListener("mouseenter",this._mouseEnterHandler=function(){r.active&&r.pointerEnabled});var w=1/60,B=null;g.addEventListener("wheel",this._mouseWheelHandler=function(e){if(r.active&&r.pointerEnabled){var t=performance.now()/1e3,i=null!==B?t-B:0;B=t,i>.05&&(i=.05),i0?i.cameraFlight.flyTo(Vd,(function(){i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot()})):(i.cameraFlight.jumpTo(Vd),i.pivotController.getPivoting()&&r.followPointer&&i.pivotController.showPivot())}}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.input.off(this._onSceneKeyDown)}}]),e}(),jd=function(){function e(t,i,r,s,n){var o=this;x(this,e),this._scene=t;var a=i.pickController,l=i.pivotController,u=i.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;var A=!1,c=!1,h=this._scene.canvas.canvas,d=function(e){var r;e&&e.worldPos&&(r=e.worldPos);var s=e&&e.entity?e.entity.aabb:t.aabb;if(r){var n=t.camera;$.subVec3(n.eye,n.look,[]),i.cameraFlight.flyTo({aabb:s})}else i.cameraFlight.flyTo({aabb:s})},p=t.tickify(this._canvasMouseMoveHandler=function(e){if(r.active&&r.pointerEnabled&&!A&&!c){if(u.hasSubs("rayMove")){var i=$.vec3(),n=$.vec3();$.canvasPosToWorldRay(t.canvas.canvas,t.camera.viewMatrix,t.camera.projMatrix,s.pointerCanvasPos,i,n),u.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:i,direction:n,canvasPos:s.pointerCanvasPos}},!0)}var l=u.hasSubs("hover"),h=u.hasSubs("hoverEnter"),d=u.hasSubs("hoverOut"),p=u.hasSubs("hoverOff"),f=u.hasSubs("hoverSurface"),v=u.hasSubs("hoverSnapOrSurface");if(l||h||d||p||f||v)if(a.pickCursorPos=s.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=f,a.scheduleSnapOrPick=v,a.update(),a.pickResult){if(a.pickResult.entity){var g=a.pickResult.entity.id;o._lastPickedEntityId!==g&&(void 0!==o._lastPickedEntityId&&u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),u.fire("hoverEnter",a.pickResult,!0),o._lastPickedEntityId=g)}u.fire("hover",a.pickResult,!0),(a.pickResult.worldPos||a.pickResult.snappedWorldPos)&&u.fire("hoverSurface",a.pickResult,!0)}else void 0!==o._lastPickedEntityId&&(u.fire("hoverOut",{entity:t.objects[o._lastPickedEntityId]},!0),o._lastPickedEntityId=void 0),u.fire("hoverOff",{canvasPos:a.pickCursorPos},!0)}});h.addEventListener("mousemove",p),h.addEventListener("mousedown",this._canvasMouseDownHandler=function(e){if(1===e.which&&(A=!0),3===e.which&&(c=!0),1===e.which&&r.active&&r.pointerEnabled&&(s.mouseDownClientX=e.clientX,s.mouseDownClientY=e.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!r.firstPerson&&r.followPointer&&(a.pickCursorPos=s.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),1===e.which))){var i=a.pickResult;i&&i.worldPos?(l.setPivotPos(i.worldPos),l.startPivot()):(r.smartPivot?l.setCanvasPivotPos(s.pointerCanvasPos):l.setPivotPos(t.camera.look),l.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=function(e){1===e.which&&(A=!1),3===e.which&&(c=!1),l.getPivoting()&&l.endPivot()}),h.addEventListener("mouseup",this._canvasMouseUpHandler=function(e){if(r.active&&r.pointerEnabled&&(1===e.which&&(l.hidePivot(),!(Math.abs(e.clientX-s.mouseDownClientX)>3||Math.abs(e.clientY-s.mouseDownClientY)>3)))){var n=u.hasSubs("picked"),A=u.hasSubs("pickedNothing"),c=u.hasSubs("pickedSurface"),h=u.hasSubs("doublePicked"),p=u.hasSubs("doublePickedSurface"),f=u.hasSubs("doublePickedNothing");if(!(r.doublePickFlyTo||h||p||f))return(n||A||c)&&(a.pickCursorPos=s.pointerCanvasPos,a.schedulePickEntity=!0,a.schedulePickSurface=c,a.update(),a.pickResult?(u.fire("picked",a.pickResult,!0),a.pickedSurface&&u.fire("pickedSurface",a.pickResult,!0)):u.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(o._clicks=0);if(o._clicks++,1===o._clicks){a.pickCursorPos=s.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo,a.schedulePickSurface=c,a.update();var v=a.pickResult,g=a.pickedSurface;o._timeout=setTimeout((function(){v?(u.fire("picked",v,!0),g&&(u.fire("pickedSurface",v,!0),!r.firstPerson&&r.followPointer&&(i.pivotController.setPivotPos(v.worldPos),i.pivotController.startPivot()&&i.pivotController.showPivot()))):u.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),o._clicks=0}),r.doubleClickTimeFrame)}else{if(null!==o._timeout&&(window.clearTimeout(o._timeout),o._timeout=null),a.pickCursorPos=s.pointerCanvasPos,a.schedulePickEntity=r.doublePickFlyTo||h||p,a.schedulePickSurface=a.schedulePickEntity&&p,a.update(),a.pickResult){if(u.fire("doublePicked",a.pickResult,!0),a.pickedSurface&&u.fire("doublePickedSurface",a.pickResult,!0),r.doublePickFlyTo&&(d(a.pickResult),!r.firstPerson&&r.followPointer)){var m=a.pickResult.entity.aabb,_=$.getAABB3Center(m);i.pivotController.setPivotPos(_),i.pivotController.startPivot()&&i.pivotController.showPivot()}}else if(u.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),r.doublePickFlyTo&&(d(),!r.firstPerson&&r.followPointer)){var y=t.aabb,b=$.getAABB3Center(y);i.pivotController.setPivotPos(b),i.pivotController.startPivot()&&i.pivotController.showPivot()}o._clicks=0}}},!1)}return C(e,[{key:"reset",value:function(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}},{key:"destroy",value:function(){var e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}]),e}(),Gd=function(){function e(t,i,r,s,n){x(this,e),this._scene=t;var o=t.input,a=[],l=t.canvas.canvas,u=!0;this._onSceneMouseMove=o.on("mousemove",(function(){u=!0})),this._onSceneKeyDown=o.on("keydown",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&s.mouseover&&(a[e]=!0,e===o.KEY_SHIFT&&(l.style.cursor="move"))})),this._onSceneKeyUp=o.on("keyup",(function(e){r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&(a[e]=!1,e===o.KEY_SHIFT&&(l.style.cursor=null),i.pivotController.getPivoting()&&i.pivotController.endPivot())})),this._onTick=t.on("tick",(function(e){if(r.active&&r.pointerEnabled&&t.input.keyboardEnabled&&s.mouseover){var l=i.cameraControl,A=e.deltaTime/1e3;if(!r.planView){var c=l._isKeyDownForAction(l.ROTATE_Y_POS,a),h=l._isKeyDownForAction(l.ROTATE_Y_NEG,a),d=l._isKeyDownForAction(l.ROTATE_X_POS,a),p=l._isKeyDownForAction(l.ROTATE_X_NEG,a),f=A*r.keyboardRotationRate;(c||h||d||p)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),c?n.rotateDeltaY+=f:h&&(n.rotateDeltaY-=f),d?n.rotateDeltaX+=f:p&&(n.rotateDeltaX-=f),!r.firstPerson&&r.followPointer&&i.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){var v=l._isKeyDownForAction(l.DOLLY_BACKWARDS,a),g=l._isKeyDownForAction(l.DOLLY_FORWARDS,a);if(v||g){var m=A*r.keyboardDollyRate;!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),g?n.dollyDelta-=m:v&&(n.dollyDelta+=m),u&&(s.followPointerDirty=!0,u=!1)}}var _=l._isKeyDownForAction(l.PAN_FORWARDS,a),y=l._isKeyDownForAction(l.PAN_BACKWARDS,a),b=l._isKeyDownForAction(l.PAN_LEFT,a),w=l._isKeyDownForAction(l.PAN_RIGHT,a),B=l._isKeyDownForAction(l.PAN_UP,a),x=l._isKeyDownForAction(l.PAN_DOWN,a),P=(a[o.KEY_ALT]?.3:1)*A*r.keyboardPanRate;(_||y||b||w||B||x)&&(!r.firstPerson&&r.followPointer&&i.pivotController.startPivot(),x?n.panDeltaY+=P:B&&(n.panDeltaY+=-P),w?n.panDeltaX+=-P:b&&(n.panDeltaX+=P),y?n.panDeltaZ+=P:_&&(n.panDeltaZ+=-P))}}))}return C(e,[{key:"reset",value:function(){}},{key:"destroy",value:function(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),this._scene.input.off(this._onSceneKeyUp)}}]),e}(),zd=$.vec3(),Wd=function(){function e(t,i,r,s,n){x(this,e),this._scene=t;var o=t.camera,a=i.pickController,l=i.pivotController,u=i.panController,A=1,c=1,h=null;this._onTick=t.on("tick",(function(){if(r.active&&r.pointerEnabled){var e="default";if(Math.abs(n.dollyDelta)<.001&&(n.dollyDelta=0),Math.abs(n.rotateDeltaX)<.001&&(n.rotateDeltaX=0),Math.abs(n.rotateDeltaY)<.001&&(n.rotateDeltaY=0),0===n.rotateDeltaX&&0===n.rotateDeltaY||(n.dollyDelta=0),r.followPointer){if(--A<=0&&(A=1,0!==n.dollyDelta)){if(0===n.rotateDeltaY&&0===n.rotateDeltaX&&r.followPointer&&s.followPointerDirty&&(a.pickCursorPos=s.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?h=a.pickResult.worldPos:(c=1,h=null),s.followPointerDirty=!1),h){var i=Math.abs($.lenVec3($.subVec3(h,t.camera.eye,zd)));c=i/r.dollyProximityThreshold}cr.longTapRadius||Math.abs(g)>r.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),r.planView){var m=t.camera;if("perspective"===m.projection){var _=Math.abs(t.camera.eyeLookDist)*Math.tan(m.perspective.fov/2*Math.PI/180);n.panDeltaX+=v*_/l*r.touchPanRate,n.panDeltaY+=g*_/l*r.touchPanRate}else n.panDeltaX+=.5*m.ortho.scale*(v/l)*r.touchPanRate,n.panDeltaY+=.5*m.ortho.scale*(g/l)*r.touchPanRate}else n.rotateDeltaY-=v/a*(1*r.dragRotationRate),n.rotateDeltaX+=g/l*(1.5*r.dragRotationRate)}else if(2===p){var y=d[0],b=d[1];Yd(y,u),Yd(b,A);var w=$.geometricMeanVec2(h[0],h[1]),B=$.geometricMeanVec2(u,A),x=$.vec2();$.subVec2(w,B,x);var P=x[0],C=x[1],M=t.camera,E=$.distVec2([y.pageX,y.pageY],[b.pageX,b.pageY]),F=($.distVec2(h[0],h[1])-E)*r.touchDollyRate;if(n.dollyDelta=F,Math.abs(F)<1)if("perspective"===M.projection){var k=o.pickResult?o.pickResult.worldPos:t.center,I=Math.abs($.lenVec3($.subVec3(k,t.camera.eye,[])))*Math.tan(M.perspective.fov/2*Math.PI/180);n.panDeltaX-=P*I/l*r.touchPanRate,n.panDeltaY-=C*I/l*r.touchPanRate}else n.panDeltaX-=.5*M.ortho.scale*(P/l)*r.touchPanRate,n.panDeltaY-=.5*M.ortho.scale*(C/l)*r.touchPanRate;s.pointerCanvasPos=B}for(var D=0;D-1&&t-c<150&&(h>-1&&c-h<325?(Zd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("doublePicked",a.pickResult),a.pickedSurface&&l.fire("doublePickedSurface",a.pickResult),r.doublePickFlyTo&&p(a.pickResult)):(l.fire("doublePickedNothing"),r.doublePickFlyTo&&p()),h=-1):$.distVec2(u[0],A)<4&&(Zd(n[0],a.pickCursorPos),a.schedulePickEntity=!0,a.schedulePickSurface=o,a.update(),a.pickResult?(a.pickResult.touchInput=!0,l.fire("picked",a.pickResult),a.pickedSurface&&l.fire("pickedSurface",a.pickResult)):l.fire("pickedNothing"),h=t),c=-1),u.length=i.length;for(var d=0,f=i.length;d1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,e,s)).PAN_LEFT=0,r.PAN_RIGHT=1,r.PAN_UP=2,r.PAN_DOWN=3,r.PAN_FORWARDS=4,r.PAN_BACKWARDS=5,r.ROTATE_X_POS=6,r.ROTATE_X_NEG=7,r.ROTATE_Y_POS=8,r.ROTATE_Y_NEG=9,r.DOLLY_FORWARDS=10,r.DOLLY_BACKWARDS=11,r.AXIS_VIEW_RIGHT=12,r.AXIS_VIEW_BACK=13,r.AXIS_VIEW_LEFT=14,r.AXIS_VIEW_FRONT=15,r.AXIS_VIEW_TOP=16,r.AXIS_VIEW_BOTTOM=17,r._keyMap={},r.scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},r._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,snapToVertex:true,snapToEdge:true,snapRadius:30,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},r._states={pointerCanvasPos:$.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:$.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},r._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};var n=r.scene;return r._controllers={cameraControl:b(r),pickController:new Sd(b(r),r._configs),pivotController:new Dd(n,r._configs),panController:new Pd(n),cameraFlight:new Wh(b(r),{duration:.5})},r._handlers=[new Kd(r.scene,r._controllers,r._configs,r._states,r._updates),new Jd(r.scene,r._controllers,r._configs,r._states,r._updates),new Ld(r.scene,r._controllers,r._configs,r._states,r._updates),new Hd(r.scene,r._controllers,r._configs,r._states,r._updates),new jd(r.scene,r._controllers,r._configs,r._states,r._updates),new qd(r.scene,r._controllers,r._configs,r._states,r._updates),new Gd(r.scene,r._controllers,r._configs,r._states,r._updates)],r._cameraUpdater=new Wd(r.scene,r._controllers,r._configs,r._states,r._updates),r.navMode=s.navMode,s.planView&&(r.planView=s.planView),r.constrainVertical=s.constrainVertical,s.keyboardLayout?r.keyboardLayout=s.keyboardLayout:r.keyMap=s.keyMap,r.doublePickFlyTo=s.doublePickFlyTo,r.panRightClick=s.panRightClick,r.active=s.active,r.followPointer=s.followPointer,r.rotationInertia=s.rotationInertia,r.keyboardPanRate=s.keyboardPanRate,r.touchPanRate=s.touchPanRate,r.keyboardRotationRate=s.keyboardRotationRate,r.dragRotationRate=s.dragRotationRate,r.touchDollyRate=s.touchDollyRate,r.dollyInertia=s.dollyInertia,r.dollyProximityThreshold=s.dollyProximityThreshold,r.dollyMinSpeed=s.dollyMinSpeed,r.panInertia=s.panInertia,r.pointerEnabled=!0,r.keyboardDollyRate=s.keyboardDollyRate,r.mouseWheelDollyRate=s.mouseWheelDollyRate,r}return C(i,[{key:"keyMap",get:function(){return this._keyMap},set:function(e){if(e=e||"qwerty",le.isString(e)){var t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{var r=e;this._keyMap=r}}},{key:"_isKeyDownForAction",value:function(e,t){var i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(var r=0,s=i.length;r0&&void 0!==arguments[0]?arguments[0]:{};this._controllers.pivotController.enablePivotSphere(e)}},{key:"disablePivotSphere",value:function(){this._controllers.pivotController.disablePivotSphere()}},{key:"smartPivot",get:function(){return this._configs.smartPivot},set:function(e){this._configs.smartPivot=!1!==e}},{key:"doubleClickTimeFrame",get:function(){return this._configs.doubleClickTimeFrame},set:function(e){this._configs.doubleClickTimeFrame=null!=e?e:250}},{key:"destroy",value:function(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),f(w(i.prototype),"destroy",this).call(this)}},{key:"_destroyHandlers",value:function(){for(var e=0,t=this._handlers.length;e1&&void 0!==arguments[1]?arguments[1]:{};if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);var i=this.metaScene,r=e.properties;if(e.propertySets)for(var s=0,n=e.propertySets.length;s0?np(t):null,o=i&&i.length>0?np(i):null;return function e(t){if(t){var i=!0;(o&&o[t.type]||n&&!n[t.type])&&(i=!1),i&&r.push(t.id);var s=t.children;if(s)for(var a=0,l=s.length;a * Copyright (c) 2022 Niklas von Hertzen @@ -33,4 +33,4 @@ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */var op=function(e,t){return op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},op(e,t)};function ap(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}op(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var lp=function(){return lp=Object.assign||function(e){for(var t,i=1,s=arguments.length;i0&&r[r.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!r||n[1]>r[0]&&n[1]=55296&&r<=56319&&i>10),o%1024+56320)),(r+1===i||s.length>16384)&&(n+=String.fromCharCode.apply(String,s),s.length=0)}return n},vp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),mp=0;mp=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),xp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Pp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Cp=0;Cp>4,A[l++]=(15&s)<<4|r>>2,A[l++]=(3&r)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],s=0;s0;){var o=s[--n];if(Array.isArray(e)?-1!==e.indexOf(o):e===o)for(var a=i;a<=s.length;){var l;if((l=s[++a])===t)return!0;if(l!==Mp)break}if(o!==Mp)break}return!1},lf=function(e,t){for(var i=e;i>=0;){var s=t[i];if(s!==Mp)return s;i--}return 0},uf=function(e,t,i,s,r){if(0===i[s])return"×";var n=s-1;if(Array.isArray(r)&&!0===r[n])return"×";var o=n-1,a=n+1,l=t[n],u=o>=0?t[o]:0,A=t[a];if(2===l&&3===A)return"×";if(-1!==ef.indexOf(l))return"!";if(-1!==ef.indexOf(A))return"×";if(-1!==tf.indexOf(A))return"×";if(8===lf(n,t))return"÷";if(11===qp.get(e[n]))return"×";if((l===Hp||l===jp)&&11===qp.get(e[a]))return"×";if(7===l||7===A)return"×";if(9===l)return"×";if(-1===[Mp,Ep,Fp].indexOf(l)&&9===A)return"×";if(-1!==[kp,Ip,Dp,Rp,Qp].indexOf(A))return"×";if(lf(n,t)===Lp)return"×";if(af(23,Lp,n,t))return"×";if(af([kp,Ip],Tp,n,t))return"×";if(af(12,12,n,t))return"×";if(l===Mp)return"÷";if(23===l||23===A)return"×";if(16===A||16===l)return"÷";if(-1!==[Ep,Fp,Tp].indexOf(A)||14===l)return"×";if(36===u&&-1!==of.indexOf(l))return"×";if(l===Qp&&36===A)return"×";if(A===Sp)return"×";if(-1!==$p.indexOf(A)&&l===Up||-1!==$p.indexOf(l)&&A===Up)return"×";if(l===Np&&-1!==[Wp,Hp,jp].indexOf(A)||-1!==[Wp,Hp,jp].indexOf(l)&&A===Op)return"×";if(-1!==$p.indexOf(l)&&-1!==sf.indexOf(A)||-1!==sf.indexOf(l)&&-1!==$p.indexOf(A))return"×";if(-1!==[Np,Op].indexOf(l)&&(A===Up||-1!==[Lp,Fp].indexOf(A)&&t[a+1]===Up)||-1!==[Lp,Fp].indexOf(l)&&A===Up||l===Up&&-1!==[Up,Qp,Rp].indexOf(A))return"×";if(-1!==[Up,Qp,Rp,kp,Ip].indexOf(A))for(var c=n;c>=0;){if((h=t[c])===Up)return"×";if(-1===[Qp,Rp].indexOf(h))break;c--}if(-1!==[Np,Op].indexOf(A))for(c=-1!==[kp,Ip].indexOf(l)?o:n;c>=0;){var h;if((h=t[c])===Up)return"×";if(-1===[Qp,Rp].indexOf(h))break;c--}if(Kp===l&&-1!==[Kp,Xp,Gp,zp].indexOf(A)||-1!==[Xp,Gp].indexOf(l)&&-1!==[Xp,Yp].indexOf(A)||-1!==[Yp,zp].indexOf(l)&&A===Yp)return"×";if(-1!==nf.indexOf(l)&&-1!==[Sp,Op].indexOf(A)||-1!==nf.indexOf(A)&&l===Np)return"×";if(-1!==$p.indexOf(l)&&-1!==$p.indexOf(A))return"×";if(l===Rp&&-1!==$p.indexOf(A))return"×";if(-1!==$p.concat(Up).indexOf(l)&&A===Lp&&-1===Zp.indexOf(e[a])||-1!==$p.concat(Up).indexOf(A)&&l===Ip)return"×";if(41===l&&41===A){for(var d=i[n],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===Hp&&A===jp?"×":"÷"},Af=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],s=[],r=[];return e.forEach((function(e,n){var o=qp.get(e);if(o>50?(r.push(!0),o-=50):r.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return s.push(n),i.push(16);if(4===o||11===o){if(0===n)return s.push(n),i.push(Vp);var a=i[n-1];return-1===rf.indexOf(a)?(s.push(s[n-1]),i.push(a)):(s.push(n),i.push(Vp))}return s.push(n),31===o?i.push("strict"===t?Tp:Wp):o===Jp||29===o?i.push(Vp):43===o?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Wp):i.push(Vp):void i.push(o)})),[s,i,r]}(e,t.lineBreak),s=i[0],r=i[1],n=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(r=r.map((function(e){return-1!==[Up,Vp,Jp].indexOf(e)?Wp:e})));var o="keep-all"===t.wordBreak?n.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[s,r,o]},cf=function(){function e(e,t,i,s){this.codePoints=e,this.required="!"===t,this.start=i,this.end=s}return e.prototype.slice=function(){return fp.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),hf=function(e){return e>=48&&e<=57},df=function(e){return hf(e)||e>=65&&e<=70||e>=97&&e<=102},pf=function(e){return 10===e||9===e||32===e},ff=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},vf=function(e){return ff(e)||hf(e)||45===e},gf=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},mf=function(e,t){return 92===e&&10!==t},_f=function(e,t,i){return 45===e?ff(t)||mf(t,i):!!ff(e)||!(92!==e||!mf(e,t))},yf=function(e,t,i){return 43===e||45===e?!!hf(t)||46===t&&hf(i):hf(46===e?t:e)},bf=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var s=[];hf(e[t]);)s.push(e[t++]);var r=s.length?parseInt(fp.apply(void 0,s),10):0;46===e[t]&&t++;for(var n=[];hf(e[t]);)n.push(e[t++]);var o=n.length,a=o?parseInt(fp.apply(void 0,n),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var u=[];hf(e[t]);)u.push(e[t++]);var A=u.length?parseInt(fp.apply(void 0,u),10):0;return i*(r+a*Math.pow(10,-o))*Math.pow(10,l*A)},wf={type:2},Bf={type:3},xf={type:4},Pf={type:13},Cf={type:8},Mf={type:21},Ef={type:9},Ff={type:10},kf={type:11},If={type:12},Df={type:14},Sf={type:23},Tf={type:1},Lf={type:25},Rf={type:24},Uf={type:26},Of={type:27},Nf={type:28},Qf={type:29},Vf={type:31},Hf={type:32},jf=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(pp(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==Hf;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),s=this.peekCodePoint(2);if(vf(t)||mf(i,s)){var r=_f(t,i,s)?2:1;return{type:5,value:this.consumeName(),flags:r}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Pf;break;case 39:return this.consumeStringToken(39);case 40:return wf;case 41:return Bf;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Df;break;case 43:if(yf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return xf;case 45:var n=e,o=this.peekCodePoint(0),a=this.peekCodePoint(1);if(yf(n,o,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(_f(n,o,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===o&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),Rf;break;case 46:if(yf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return Uf;case 59:return Of;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),Lf;break;case 64:var u=this.peekCodePoint(0),A=this.peekCodePoint(1),c=this.peekCodePoint(2);if(_f(u,A,c))return{type:7,value:this.consumeName()};break;case 91:return Nf;case 92:if(mf(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return Qf;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Cf;break;case 123:return kf;case 125:return If;case 117:case 85:var h=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==h||!df(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Ef;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),Mf;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Ff;break;case-1:return Hf}return pf(e)?(this.consumeWhiteSpace(),Vf):hf(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):ff(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:fp(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();df(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(fp.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(fp.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var s=parseInt(fp.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&df(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var r=[];df(t)&&r.length<6;)r.push(t),t=this.consumeCodePoint();return{type:30,start:s,end:parseInt(fp.apply(void 0,r),16)}}return{type:30,start:s,end:s}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),Sf)}for(;;){var s=this.consumeCodePoint();if(-1===s||41===s)return{type:22,value:fp.apply(void 0,e)};if(pf(s))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:fp.apply(void 0,e)}):(this.consumeBadUrlRemnants(),Sf);if(34===s||39===s||40===s||gf(s))return this.consumeBadUrlRemnants(),Sf;if(92===s){if(!mf(s,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),Sf;e.push(this.consumeEscapedCodePoint())}else e.push(s)}},e.prototype.consumeWhiteSpace=function(){for(;pf(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;mf(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=fp.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var s=this._value[i];if(-1===s||void 0===s||s===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===s)return this._value.splice(0,i),Tf;if(92===s){var r=this._value[i+1];-1!==r&&void 0!==r&&(10===r?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):mf(s,r)&&(t+=this.consumeStringSlice(i),t+=fp(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var s=this.peekCodePoint(1);if(46===i&&hf(s))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),s=this.peekCodePoint(1);var r=this.peekCodePoint(2);if((69===i||101===i)&&((43===s||45===s)&&hf(r)||hf(s)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[bf(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],s=this.peekCodePoint(0),r=this.peekCodePoint(1),n=this.peekCodePoint(2);return _f(s,r,n)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===s?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(df(e)){for(var t=fp(e);df(this.peekCodePoint(0))&&t.length<6;)t+=fp(this.consumeCodePoint());pf(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(vf(t))e+=fp(t);else{if(!mf(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=fp(this.consumeEscapedCodePoint())}}},e}(),Gf=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new jf;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||$f(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?Hf:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),zf=function(e){return 15===e.type},Wf=function(e){return 17===e.type},Kf=function(e){return 20===e.type},Xf=function(e){return 0===e.type},Yf=function(e,t){return Kf(e)&&e.value===t},Jf=function(e){return 31!==e.type},Zf=function(e){return 31!==e.type&&4!==e.type},qf=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},$f=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},ev=function(e){return 17===e.type||15===e.type},tv=function(e){return 16===e.type||ev(e)},iv=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},sv={type:17,number:0,flags:4},rv={type:16,number:50,flags:4},nv={type:16,number:100,flags:4},ov=function(e,t,i){var s=e[0],r=e[1];return[av(s,t),av(void 0!==r?r:s,i)]},av=function(e,t){if(16===e.type)return e.number/100*t;if(zf(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},lv=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},uv=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Av=function(e){switch(e.filter(Kf).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[sv,sv];case"to top":case"bottom":return cv(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[sv,nv];case"to right":case"left":return cv(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[nv,nv];case"to bottom":case"top":return cv(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[nv,sv];case"to left":case"right":return cv(270)}return 0},cv=function(e){return Math.PI*e/180},hv=function(e,t){if(18===t.type){var i=yv[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var s=t.value.substring(0,1),r=t.value.substring(1,2),n=t.value.substring(2,3);return fv(parseInt(s+s,16),parseInt(r+r,16),parseInt(n+n,16),1)}if(4===t.value.length){s=t.value.substring(0,1),r=t.value.substring(1,2),n=t.value.substring(2,3);var o=t.value.substring(3,4);return fv(parseInt(s+s,16),parseInt(r+r,16),parseInt(n+n,16),parseInt(o+o,16)/255)}if(6===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),n=t.value.substring(4,6);return fv(parseInt(s,16),parseInt(r,16),parseInt(n,16),1)}if(8===t.value.length){s=t.value.substring(0,2),r=t.value.substring(2,4),n=t.value.substring(4,6),o=t.value.substring(6,8);return fv(parseInt(s,16),parseInt(r,16),parseInt(n,16),parseInt(o,16)/255)}}if(20===t.type){var a=wv[t.value.toUpperCase()];if(void 0!==a)return a}return wv.TRANSPARENT},dv=function(e){return 0==(255&e)},pv=function(e){var t=255&e,i=255&e>>8,s=255&e>>16,r=255&e>>24;return t<255?"rgba("+r+","+s+","+i+","+t/255+")":"rgb("+r+","+s+","+i+")"},fv=function(e,t,i,s){return(e<<24|t<<16|i<<8|Math.round(255*s)<<0)>>>0},vv=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},gv=function(e,t){var i=t.filter(Zf);if(3===i.length){var s=i.map(vv),r=s[0],n=s[1],o=s[2];return fv(r,n,o,1)}if(4===i.length){var a=i.map(vv),l=(r=a[0],n=a[1],o=a[2],a[3]);return fv(r,n,o,l)}return 0};function mv(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var _v=function(e,t){var i=t.filter(Zf),s=i[0],r=i[1],n=i[2],o=i[3],a=(17===s.type?cv(s.number):lv(e,s))/(2*Math.PI),l=tv(r)?r.number/100:0,u=tv(n)?n.number/100:0,A=void 0!==o&&tv(o)?av(o,1):1;if(0===l)return fv(255*u,255*u,255*u,1);var c=u<=.5?u*(l+1):u+l-u*l,h=2*u-c,d=mv(h,c,a+1/3),p=mv(h,c,a),f=mv(h,c,a-1/3);return fv(255*d,255*p,255*f,A)},yv={hsl:_v,hsla:_v,rgb:gv,rgba:gv},bv=function(e,t){return hv(e,Gf.create(t).parseComponentValue())},wv={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},Bv={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Kf(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},xv={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Pv=function(e,t){var i=hv(e,t[0]),s=t[1];return s&&tv(s)?{color:i,stop:s}:{color:i,stop:null}},Cv=function(e,t){var i=e[0],s=e[e.length-1];null===i.stop&&(i.stop=sv),null===s.stop&&(s.stop=nv);for(var r=[],n=0,o=0;on?r.push(l):r.push(n),n=l}else r.push(null)}var u=null;for(o=0;oe.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:r?1/0:-1/0,optimumCorner:null}).optimumCorner},kv=function(e,t){var i=cv(180),s=[];return qf(t).forEach((function(t,r){if(0===r){var n=t[0];if(20===n.type&&-1!==["top","left","right","bottom"].indexOf(n.value))return void(i=Av(t));if(uv(n))return void(i=(lv(e,n)+cv(270))%cv(360))}var o=Pv(e,t);s.push(o)})),{angle:i,stops:s,type:1}},Iv=function(e,t){var i=0,s=3,r=[],n=[];return qf(t).forEach((function(t,o){var a=!0;if(0===o?a=t.reduce((function(e,t){if(Kf(t))switch(t.value){case"center":return n.push(rv),!1;case"top":case"left":return n.push(sv),!1;case"right":case"bottom":return n.push(nv),!1}else if(tv(t)||ev(t))return n.push(t),!1;return e}),a):1===o&&(a=t.reduce((function(e,t){if(Kf(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return s=0,!1;case"farthest-side":return s=1,!1;case"closest-corner":return s=2,!1;case"cover":case"farthest-corner":return s=3,!1}else if(ev(t)||tv(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)),a){var l=Pv(e,t);r.push(l)}})),{size:s,shape:i,stops:r,position:n,type:2}},Dv=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var s=Tv[t.name];if(void 0===s)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return s(e,t.values)}throw new Error("Unsupported image type "+t.type)};var Sv,Tv={"linear-gradient":function(e,t){var i=cv(180),s=[];return qf(t).forEach((function(t,r){if(0===r){var n=t[0];if(20===n.type&&"to"===n.value)return void(i=Av(t));if(uv(n))return void(i=lv(e,n))}var o=Pv(e,t);s.push(o)})),{angle:i,stops:s,type:1}},"-moz-linear-gradient":kv,"-ms-linear-gradient":kv,"-o-linear-gradient":kv,"-webkit-linear-gradient":kv,"radial-gradient":function(e,t){var i=0,s=3,r=[],n=[];return qf(t).forEach((function(t,o){var a=!0;if(0===o){var l=!1;a=t.reduce((function(e,t){if(l)if(Kf(t))switch(t.value){case"center":return n.push(rv),e;case"top":case"left":return n.push(sv),e;case"right":case"bottom":return n.push(nv),e}else(tv(t)||ev(t))&&n.push(t);else if(Kf(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return s=0,!1;case"cover":case"farthest-side":return s=1,!1;case"contain":case"closest-corner":return s=2,!1;case"farthest-corner":return s=3,!1}else if(ev(t)||tv(t))return Array.isArray(s)||(s=[]),s.push(t),!1;return e}),a)}if(a){var u=Pv(e,t);r.push(u)}})),{size:s,shape:i,stops:r,position:n,type:2}},"-moz-radial-gradient":Iv,"-ms-radial-gradient":Iv,"-o-radial-gradient":Iv,"-webkit-radial-gradient":Iv,"-webkit-gradient":function(e,t){var i=cv(180),s=[],r=1;return qf(t).forEach((function(t,i){var n=t[0];if(0===i){if(Kf(n)&&"linear"===n.value)return void(r=1);if(Kf(n)&&"radial"===n.value)return void(r=2)}if(18===n.type)if("from"===n.name){var o=hv(e,n.values[0]);s.push({stop:sv,color:o})}else if("to"===n.name){o=hv(e,n.values[0]);s.push({stop:nv,color:o})}else if("color-stop"===n.name){var a=n.values.filter(Zf);if(2===a.length){o=hv(e,a[1]);var l=a[0];Wf(l)&&s.push({stop:{type:16,number:100*l.number,flags:l.flags},color:o})}}})),1===r?{angle:(i+cv(180))%cv(360),stops:s,type:r}:{size:3,shape:0,stops:s,position:[],type:r}}},Lv={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Zf(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!Tv[e.name])}(e)})).map((function(t){return Dv(e,t)}))}},Rv={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Kf(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},Uv={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return qf(t).map((function(e){return e.filter(tv)})).map(iv)}},Ov={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return qf(t).map((function(e){return e.filter(Kf).map((function(e){return e.value})).join(" ")})).map(Nv)}},Nv=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(Sv||(Sv={}));var Qv,Vv={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return qf(t).map((function(e){return e.filter(Hv)}))}},Hv=function(e){return Kf(e)||tv(e)},jv=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Gv=jv("top"),zv=jv("right"),Wv=jv("bottom"),Kv=jv("left"),Xv=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return iv(t.filter(tv))}}},Yv=Xv("top-left"),Jv=Xv("top-right"),Zv=Xv("bottom-right"),qv=Xv("bottom-left"),$v=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},eg=$v("top"),tg=$v("right"),ig=$v("bottom"),sg=$v("left"),rg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return zf(t)?t.number:0}}},ng=rg("top"),og=rg("right"),ag=rg("bottom"),lg=rg("left"),ug={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Ag={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},cg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Kf).reduce((function(e,t){return e|hg(t.value)}),0)}},hg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},dg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},pg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(Qv||(Qv={}));var fg,vg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?Qv.STRICT:Qv.NORMAL}},gg={name:"line-height",initialValue:"normal",prefix:!1,type:4},mg=function(e,t){return Kf(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:tv(e)?av(e,t):t},_g={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:Dv(e,t)}},yg={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},bg={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},wg=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},Bg=wg("top"),xg=wg("right"),Pg=wg("bottom"),Cg=wg("left"),Mg={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Kf).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},Eg={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},Fg=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},kg=Fg("top"),Ig=Fg("right"),Dg=Fg("bottom"),Sg=Fg("left"),Tg={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},Lg={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},Rg={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Yf(t[0],"none")?[]:qf(t).map((function(t){for(var i={color:wv.TRANSPARENT,offsetX:sv,offsetY:sv,blur:sv},s=0,r=0;r1?1:0],this.overflowWrap=fm(e,Eg,t.overflowWrap),this.paddingTop=fm(e,kg,t.paddingTop),this.paddingRight=fm(e,Ig,t.paddingRight),this.paddingBottom=fm(e,Dg,t.paddingBottom),this.paddingLeft=fm(e,Sg,t.paddingLeft),this.paintOrder=fm(e,um,t.paintOrder),this.position=fm(e,Lg,t.position),this.textAlign=fm(e,Tg,t.textAlign),this.textDecorationColor=fm(e,Xg,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=fm(e,Yg,null!==(s=t.textDecorationLine)&&void 0!==s?s:t.textDecoration),this.textShadow=fm(e,Rg,t.textShadow),this.textTransform=fm(e,Ug,t.textTransform),this.transform=fm(e,Og,t.transform),this.transformOrigin=fm(e,Hg,t.transformOrigin),this.visibility=fm(e,jg,t.visibility),this.webkitTextStrokeColor=fm(e,Am,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=fm(e,cm,t.webkitTextStrokeWidth),this.wordBreak=fm(e,Gg,t.wordBreak),this.zIndex=fm(e,zg,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return dv(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return tm(this.display,4)||tm(this.display,33554432)||tm(this.display,268435456)||tm(this.display,536870912)||tm(this.display,67108864)||tm(this.display,134217728)},e}(),dm=function(e,t){this.content=fm(e,im,t.content),this.quotes=fm(e,om,t.quotes)},pm=function(e,t){this.counterIncrement=fm(e,sm,t.counterIncrement),this.counterReset=fm(e,rm,t.counterReset)},fm=function(e,t,i){var s=new jf,r=null!=i?i.toString():t.initialValue;s.write(r);var n=new Gf(s.read());switch(t.type){case 2:var o=n.parseComponentValue();return t.parse(e,Kf(o)?o.value:t.initialValue);case 0:return t.parse(e,n.parseComponentValue());case 1:return t.parse(e,n.parseComponentValues());case 4:return n.parseComponentValue();case 3:switch(t.format){case"angle":return lv(e,n.parseComponentValue());case"color":return hv(e,n.parseComponentValue());case"image":return Dv(e,n.parseComponentValue());case"length":var a=n.parseComponentValue();return ev(a)?a:sv;case"length-percentage":var l=n.parseComponentValue();return tv(l)?l:sv;case"time":return Wg(e,n.parseComponentValue())}}},vm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},gm=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,vm(t,3),this.styles=new hm(e,window.getComputedStyle(t,null)),g_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=dp(this.context,t),vm(t,4)&&(this.flags|=16)},mm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_m="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ym=0;ym=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),Bm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Pm=0;Pm>10),o%1024+56320)),(r+1===i||s.length>16384)&&(n+=String.fromCharCode.apply(String,s),s.length=0)}return n},Dm=function(e,t){var i,s,r,n=function(e){var t,i,s,r,n,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var u="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(o):new Array(o),A=Array.isArray(u)?u:new Uint8Array(u);for(t=0;t>4,A[l++]=(15&s)<<4|r>>2,A[l++]=(3&r)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],s=0;s=55296&&r<=56319&&i=i)return{done:!0,value:null};for(var e="×";so.x||r.y>o.y;return o=r,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(Nm,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),s=i.getContext("2d");if(!s)return!1;t.src="data:image/svg+xml,";try{s.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(Nm,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var s=t.getContext("2d");if(!s)return Promise.reject(!1);s.fillStyle="rgb(0, 255, 0)",s.fillRect(0,0,i,i);var r=new Image,n=t.toDataURL();r.src=n;var o=Um(i,i,0,0,r);return s.fillStyle="red",s.fillRect(0,0,i,i),Om(o).then((function(t){s.drawImage(t,0,0);var r=s.getImageData(0,0,i,i).data;s.fillStyle="red",s.fillRect(0,0,i,i);var o=e.createElement("div");return o.style.backgroundImage="url("+n+")",o.style.height="100px",Rm(r)?Om(Um(i,i,0,0,o)):Promise.reject(!1)})).then((function(e){return s.drawImage(e,0,0),Rm(s.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(Nm,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(Nm,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(Nm,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(Nm,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(Nm,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},Qm=function(e,t){this.text=e,this.bounds=t},Vm=function(e,t){var i=t.ownerDocument;if(i){var s=i.createElement("html2canvaswrapper");s.appendChild(t.cloneNode(!0));var r=t.parentNode;if(r){r.replaceChild(s,t);var n=dp(e,s);return s.firstChild&&r.replaceChild(s.firstChild,s),n}}return hp.EMPTY},Hm=function(e,t,i){var s=e.ownerDocument;if(!s)throw new Error("Node has no owner document");var r=s.createRange();return r.setStart(e,t),r.setEnd(e,t+i),r},jm=function(e){if(Nm.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=Lm(e),s=[];!(t=i.next()).done;)t.value&&s.push(t.value.slice());return s}(e)},Gm=function(e,t){return 0!==t.letterSpacing?jm(e):function(e,t){if(Nm.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return Wm(e,t)}(e,t)},zm=[32,160,4961,65792,65793,4153,4241],Wm=function(e,t){for(var i,s=function(e,t){var i=pp(e),s=Af(i,t),r=s[0],n=s[1],o=s[2],a=i.length,l=0,u=0;return{next:function(){if(u>=a)return{done:!0,value:null};for(var e="×";u0)if(Nm.SUPPORT_RANGE_BOUNDS){var r=Hm(s,o,t.length).getClientRects();if(r.length>1){var a=jm(t),l=0;a.forEach((function(t){n.push(new Qm(t,hp.fromDOMRectList(e,Hm(s,l+o,t.length).getClientRects()))),l+=t.length}))}else n.push(new Qm(t,hp.fromDOMRectList(e,r)))}else{var u=s.splitText(t.length);n.push(new Qm(t,Vm(e,s))),s=u}else Nm.SUPPORT_RANGE_BOUNDS||(s=s.splitText(t.length));o+=t.length})),n}(e,this.text,i,t)},Xm=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(Ym,Jm);case 2:return e.toUpperCase();default:return e}},Ym=/(^|\s|:|-|\(|\))([a-z])/g,Jm=function(e,t,i){return e.length>0?t+i.toUpperCase():e},Zm=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.src=i.currentSrc||i.src,s.intrinsicWidth=i.naturalWidth,s.intrinsicHeight=i.naturalHeight,s.context.cache.addImage(s.src),s}return ap(t,e),t}(gm),qm=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.canvas=i,s.intrinsicWidth=i.width,s.intrinsicHeight=i.height,s}return ap(t,e),t}(gm),$m=function(e){function t(t,i){var s=e.call(this,t,i)||this,r=new XMLSerializer,n=dp(t,i);return i.setAttribute("width",n.width+"px"),i.setAttribute("height",n.height+"px"),s.svg="data:image/svg+xml,"+encodeURIComponent(r.serializeToString(i)),s.intrinsicWidth=i.width.baseVal.value,s.intrinsicHeight=i.height.baseVal.value,s.context.cache.addImage(s.svg),s}return ap(t,e),t}(gm),e_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.value=i.value,s}return ap(t,e),t}(gm),t_=function(e){function t(t,i){var s=e.call(this,t,i)||this;return s.start=i.start,s.reversed="boolean"==typeof i.reversed&&!0===i.reversed,s}return ap(t,e),t}(gm),i_=[{type:15,flags:0,unit:"px",number:3}],s_=[{type:16,flags:0,number:50}],r_="password",n_=function(e){function t(t,i){var s,r=e.call(this,t,i)||this;switch(r.type=i.type.toLowerCase(),r.checked=i.checked,r.value=function(e){var t=e.type===r_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==r.type&&"radio"!==r.type||(r.styles.backgroundColor=3739148031,r.styles.borderTopColor=r.styles.borderRightColor=r.styles.borderBottomColor=r.styles.borderLeftColor=2779096575,r.styles.borderTopWidth=r.styles.borderRightWidth=r.styles.borderBottomWidth=r.styles.borderLeftWidth=1,r.styles.borderTopStyle=r.styles.borderRightStyle=r.styles.borderBottomStyle=r.styles.borderLeftStyle=1,r.styles.backgroundClip=[0],r.styles.backgroundOrigin=[0],r.bounds=(s=r.bounds).width>s.height?new hp(s.left+(s.width-s.height)/2,s.top,s.height,s.height):s.width0)s.textNodes.push(new Km(t,n,s.styles));else if(v_(n))if(I_(n)&&n.assignedNodes)n.assignedNodes().forEach((function(i){return e(t,i,s,r)}));else{var a=c_(t,n);a.styles.isVisible()&&(d_(n,a,r)?a.flags|=4:p_(a.styles)&&(a.flags|=2),-1!==u_.indexOf(n.tagName)&&(a.flags|=8),s.elements.push(a),n.slot,n.shadowRoot?e(t,n.shadowRoot,a,r):F_(n)||w_(n)||k_(n)||e(t,n,a,r))}},c_=function(e,t){return C_(t)?new Zm(e,t):x_(t)?new qm(e,t):w_(t)?new $m(e,t):__(t)?new e_(e,t):y_(t)?new t_(e,t):b_(t)?new n_(e,t):k_(t)?new o_(e,t):F_(t)?new a_(e,t):M_(t)?new l_(e,t):new gm(e,t)},h_=function(e,t){var i=c_(e,t);return i.flags|=4,A_(e,t,i,i),i},d_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||B_(e)&&i.styles.isTransparent()},p_=function(e){return e.isPositioned()||e.isFloating()},f_=function(e){return e.nodeType===Node.TEXT_NODE},v_=function(e){return e.nodeType===Node.ELEMENT_NODE},g_=function(e){return v_(e)&&void 0!==e.style&&!m_(e)},m_=function(e){return"object"===B(e.className)},__=function(e){return"LI"===e.tagName},y_=function(e){return"OL"===e.tagName},b_=function(e){return"INPUT"===e.tagName},w_=function(e){return"svg"===e.tagName},B_=function(e){return"BODY"===e.tagName},x_=function(e){return"CANVAS"===e.tagName},P_=function(e){return"VIDEO"===e.tagName},C_=function(e){return"IMG"===e.tagName},M_=function(e){return"IFRAME"===e.tagName},E_=function(e){return"STYLE"===e.tagName},F_=function(e){return"TEXTAREA"===e.tagName},k_=function(e){return"SELECT"===e.tagName},I_=function(e){return"SLOT"===e.tagName},D_=function(e){return e.tagName.indexOf("-")>0},S_=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,s=e.counterReset,r=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(r=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var n=[];return r&&s.forEach((function(e){var i=t.counters[e.counter];n.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),n},e}(),T_={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},L_={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},R_={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},U_={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},O_=function(e,t,i,s,r,n){return ei?j_(e,r,n.length>0):s.integers.reduce((function(t,i,r){for(;e>=i;)e-=i,t+=s.values[r];return t}),"")+n},N_=function(e,t,i,s){var r="";do{i||e--,r=s(e)+r,e/=t}while(e*t>=t);return r},Q_=function(e,t,i,s,r){var n=i-t+1;return(e<0?"-":"")+(N_(Math.abs(e),n,s,(function(e){return fp(Math.floor(e%n)+t)}))+r)},V_=function(e,t,i){void 0===i&&(i=". ");var s=t.length;return N_(Math.abs(e),s,!1,(function(e){return t[Math.floor(e%s)]}))+i},H_=function(e,t,i,s,r,n){if(e<-9999||e>9999)return j_(e,4,r.length>0);var o=Math.abs(e),a=r;if(0===o)return t[0]+a;for(var l=0;o>0&&l<=4;l++){var u=o%10;0===u&&tm(n,1)&&""!==a?a=t[u]+a:u>1||1===u&&0===l||1===u&&1===l&&tm(n,2)||1===u&&1===l&&tm(n,4)&&e>100||1===u&&l>1&&tm(n,8)?a=t[u]+(l>0?i[l-1]:"")+a:1===u&&l>0&&(a=i[l-1]+a),o=Math.floor(o/10)}return(e<0?s:"")+a},j_=function(e,t,i){var s=i?". ":"",r=i?"、":"",n=i?", ":"",o=i?" ":"";switch(t){case 0:return"•"+o;case 1:return"◦"+o;case 2:return"◾"+o;case 5:var a=Q_(e,48,57,!0,s);return a.length<4?"0"+a:a;case 4:return V_(e,"〇一二三四五六七八九",r);case 6:return O_(e,1,3999,T_,3,s).toLowerCase();case 7:return O_(e,1,3999,T_,3,s);case 8:return Q_(e,945,969,!1,s);case 9:return Q_(e,97,122,!1,s);case 10:return Q_(e,65,90,!1,s);case 11:return Q_(e,1632,1641,!0,s);case 12:case 49:return O_(e,1,9999,L_,3,s);case 35:return O_(e,1,9999,L_,3,s).toLowerCase();case 13:return Q_(e,2534,2543,!0,s);case 14:case 30:return Q_(e,6112,6121,!0,s);case 15:return V_(e,"子丑寅卯辰巳午未申酉戌亥",r);case 16:return V_(e,"甲乙丙丁戊己庚辛壬癸",r);case 17:case 48:return H_(e,"零一二三四五六七八九","十百千萬","負",r,14);case 47:return H_(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",r,15);case 42:return H_(e,"零一二三四五六七八九","十百千萬","负",r,14);case 41:return H_(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",r,15);case 26:return H_(e,"〇一二三四五六七八九","十百千万","マイナス",r,0);case 25:return H_(e,"零壱弐参四伍六七八九","拾百千万","マイナス",r,7);case 31:return H_(e,"영일이삼사오육칠팔구","십백천만","마이너스",n,7);case 33:return H_(e,"零一二三四五六七八九","十百千萬","마이너스",n,0);case 32:return H_(e,"零壹貳參四五六七八九","拾百千","마이너스",n,7);case 18:return Q_(e,2406,2415,!0,s);case 20:return O_(e,1,19999,U_,3,s);case 21:return Q_(e,2790,2799,!0,s);case 22:return Q_(e,2662,2671,!0,s);case 22:return O_(e,1,10999,R_,3,s);case 23:return V_(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return V_(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return Q_(e,3302,3311,!0,s);case 28:return V_(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",r);case 29:return V_(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",r);case 34:return Q_(e,3792,3801,!0,s);case 37:return Q_(e,6160,6169,!0,s);case 38:return Q_(e,4160,4169,!0,s);case 39:return Q_(e,2918,2927,!0,s);case 40:return Q_(e,1776,1785,!0,s);case 43:return Q_(e,3046,3055,!0,s);case 44:return Q_(e,3174,3183,!0,s);case 45:return Q_(e,3664,3673,!0,s);case 46:return Q_(e,3872,3881,!0,s);default:return Q_(e,48,57,!0,s)}},G_=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new S_,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,s=W_(e,t);if(!s.contentWindow)return Promise.reject("Unable to find iframe window");var r=e.defaultView.pageXOffset,n=e.defaultView.pageYOffset,o=s.contentWindow,a=o.document,l=Y_(s).then((function(){return up(i,void 0,void 0,(function(){var e,i;return Ap(this,(function(r){switch(r.label){case 0:return this.scrolledElements.forEach(ey),o&&(o.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||o.scrollY===t.top&&o.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(o.scrollX-t.left,o.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:r.sent(),r.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,X_(a)]:[3,4];case 3:r.sent(),r.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return s}))]:[2,s]}}))}))}));return a.open(),a.write(q_(document.doctype)+""),$_(this.referenceElement.ownerDocument,r,n),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(vm(e,2),x_(e))return this.createCanvasClone(e);if(P_(e))return this.createVideoClone(e);if(E_(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return C_(t)&&(C_(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),D_(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Z_(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),s=e.cloneNode(!1);return s.textContent=i,s}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var s=e.cloneNode(!1);try{s.width=e.width,s.height=e.height;var r=e.getContext("2d"),n=s.getContext("2d");if(n)if(!this.options.allowTaint&&r)n.putImageData(r.getImageData(0,0,e.width,e.height),0,0);else{var o=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(o){var a=o.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}n.drawImage(e,0,0)}return s}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return s},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var s=e.ownerDocument.createElement("canvas");return s.width=e.offsetWidth,s.height=e.offsetHeight,s},e.prototype.appendChildNode=function(e,t,i){v_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&v_(t)&&E_(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var s=this,r=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;r;r=r.nextSibling)if(v_(r)&&I_(r)&&"function"==typeof r.assignedNodes){var n=r.assignedNodes();n.length&&n.forEach((function(e){return s.appendChildNode(t,e,i)}))}else this.appendChildNode(t,r,i)},e.prototype.cloneNode=function(e,t){if(f_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&v_(e)&&(g_(e)||m_(e))){var s=this.createElementClone(e);s.style.transitionProperty="none";var r=i.getComputedStyle(e),n=i.getComputedStyle(e,":before"),o=i.getComputedStyle(e,":after");this.referenceElement===e&&g_(s)&&(this.clonedReferenceElement=s),B_(s)&&sy(s);var a=this.counters.parse(new pm(this.context,r)),l=this.resolvePseudoContent(e,s,n,Cm.BEFORE);D_(e)&&(t=!0),P_(e)||this.cloneChildNodes(e,s,t),l&&s.insertBefore(l,s.firstChild);var u=this.resolvePseudoContent(e,s,o,Cm.AFTER);return u&&s.appendChild(u),this.counters.pop(a),(r&&(this.options.copyStyles||m_(e))&&!M_(e)||t)&&Z_(r,s),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([s,e.scrollLeft,e.scrollTop]),(F_(e)||k_(e))&&(F_(s)||k_(s))&&(s.value=e.value),s}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,s){var r=this;if(i){var n=i.content,o=t.ownerDocument;if(o&&n&&"none"!==n&&"-moz-alt-content"!==n&&"none"!==i.display){this.counters.parse(new pm(this.context,i));var a=new dm(this.context,i),l=o.createElement("html2canvaspseudoelement");Z_(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(o.createTextNode(t.value));else if(22===t.type){var i=o.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var s=t.values.filter(Kf);s.length&&l.appendChild(o.createTextNode(e.getAttribute(s[0].value)||""))}else if("counter"===t.name){var n=t.values.filter(Zf),u=n[0],A=n[1];if(u&&Kf(u)){var c=r.counters.getCounterValue(u.value),h=A&&Kf(A)?bg.parse(r.context,A.value):3;l.appendChild(o.createTextNode(j_(c,h,!1)))}}else if("counters"===t.name){var d=t.values.filter(Zf),p=(u=d[0],d[1]);A=d[2];if(u&&Kf(u)){var f=r.counters.getCounterValues(u.value),v=A&&Kf(A)?bg.parse(r.context,A.value):3,g=p&&0===p.type?p.value:"",m=f.map((function(e){return j_(e,v,!1)})).join(g);l.appendChild(o.createTextNode(m))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(o.createTextNode(am(a.quotes,r.quoteDepth++,!0)));break;case"close-quote":l.appendChild(o.createTextNode(am(a.quotes,--r.quoteDepth,!1)));break;default:l.appendChild(o.createTextNode(t.value))}})),l.className=ty+" "+iy;var u=s===Cm.BEFORE?" "+ty:" "+iy;return m_(t)?t.className.baseValue+=u:t.className+=u,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(Cm||(Cm={}));var z_,W_=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},K_=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},X_=function(e){return Promise.all([].slice.call(e.images,0).map(K_))},Y_=function(e){return new Promise((function(t,i){var s=e.contentWindow;if(!s)return i("No window assigned for iframe");var r=s.document;s.onload=e.onload=function(){s.onload=e.onload=null;var i=setInterval((function(){r.body.childNodes.length>0&&"complete"===r.readyState&&(clearInterval(i),t(e))}),50)}}))},J_=["all","d","content"],Z_=function(e,t){for(var i=e.length-1;i>=0;i--){var s=e.item(i);-1===J_.indexOf(s)&&t.style.setProperty(s,e.getPropertyValue(s))}return t},q_=function(e){var t="";return e&&(t+=""),t},$_=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},ey=function(e){var t=e[0],i=e[1],s=e[2];t.scrollLeft=i,t.scrollTop=s},ty="___html2canvas___pseudoelement_before",iy="___html2canvas___pseudoelement_after",sy=function(e){ry(e,"."+ty+':before{\n content: "" !important;\n display: none !important;\n}\n .'+iy+':after{\n content: "" !important;\n display: none !important;\n}')},ry=function(e,t){var i=e.ownerDocument;if(i){var s=i.createElement("style");s.textContent=t,e.appendChild(s)}},ny=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),oy=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:dy(e)||Ay(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return up(this,void 0,void 0,(function(){var t,i,s,r,n=this;return Ap(this,(function(o){switch(o.label){case 0:return t=ny.isSameOrigin(e),i=!cy(e)&&!0===this._options.useCORS&&Nm.SUPPORT_CORS_IMAGES&&!t,s=!cy(e)&&!t&&!dy(e)&&"string"==typeof this._options.proxy&&Nm.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||cy(e)||dy(e)||s||i?(r=e,s?[4,this.proxy(r)]:[3,2]):[2];case 1:r=o.sent(),o.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var s=new Image;s.onload=function(){return e(s)},s.onerror=t,(hy(r)||i)&&(s.crossOrigin="anonymous"),s.src=r,!0===s.complete&&setTimeout((function(){return e(s)}),500),n._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+n._options.imageTimeout+"ms) loading image")}),n._options.imageTimeout)}))];case 3:return[2,o.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var s=e.substring(0,256);return new Promise((function(r,n){var o=Nm.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===o)r(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return r(e.result)}),!1),e.addEventListener("error",(function(e){return n(e)}),!1),e.readAsDataURL(a.response)}else n("Failed to proxy resource "+s+" with status code "+a.status)},a.onerror=n;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+o),"text"!==o&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return n("Timed out ("+u+"ms) proxying "+s)}}a.send()}))},e}(),ay=/^data:image\/svg\+xml/i,ly=/^data:image\/.*;base64,/i,uy=/^data:image\/.*/i,Ay=function(e){return Nm.SUPPORT_SVG_DRAWING||!py(e)},cy=function(e){return uy.test(e)},hy=function(e){return ly.test(e)},dy=function(e){return"blob"===e.substr(0,4)},py=function(e){return"svg"===e.substr(-3).toLowerCase()||ay.test(e)},fy=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),vy=function(e,t,i){return new fy(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},gy=function(){function e(e,t,i,s){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=s}return e.prototype.subdivide=function(t,i){var s=vy(this.start,this.startControl,t),r=vy(this.startControl,this.endControl,t),n=vy(this.endControl,this.end,t),o=vy(s,r,t),a=vy(r,n,t),l=vy(o,a,t);return i?new e(this.start,s,o,l):new e(l,a,n,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),my=function(e){return 1===e.type},_y=function(e){var t=e.styles,i=e.bounds,s=ov(t.borderTopLeftRadius,i.width,i.height),r=s[0],n=s[1],o=ov(t.borderTopRightRadius,i.width,i.height),a=o[0],l=o[1],u=ov(t.borderBottomRightRadius,i.width,i.height),A=u[0],c=u[1],h=ov(t.borderBottomLeftRadius,i.width,i.height),d=h[0],p=h[1],f=[];f.push((r+a)/i.width),f.push((d+A)/i.width),f.push((n+p)/i.height),f.push((l+c)/i.height);var v=Math.max.apply(Math,f);v>1&&(r/=v,n/=v,a/=v,l/=v,A/=v,c/=v,d/=v,p/=v);var g=i.width-a,m=i.height-c,_=i.width-A,y=i.height-p,b=t.borderTopWidth,w=t.borderRightWidth,B=t.borderBottomWidth,x=t.borderLeftWidth,P=av(t.paddingTop,e.bounds.width),C=av(t.paddingRight,e.bounds.width),M=av(t.paddingBottom,e.bounds.width),E=av(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=r>0||n>0?yy(i.left+x/3,i.top+b/3,r-x/3,n-b/3,z_.TOP_LEFT):new fy(i.left+x/3,i.top+b/3),this.topRightBorderDoubleOuterBox=r>0||n>0?yy(i.left+g,i.top+b/3,a-w/3,l-b/3,z_.TOP_RIGHT):new fy(i.left+i.width-w/3,i.top+b/3),this.bottomRightBorderDoubleOuterBox=A>0||c>0?yy(i.left+_,i.top+m,A-w/3,c-B/3,z_.BOTTOM_RIGHT):new fy(i.left+i.width-w/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?yy(i.left+x/3,i.top+y,d-x/3,p-B/3,z_.BOTTOM_LEFT):new fy(i.left+x/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=r>0||n>0?yy(i.left+2*x/3,i.top+2*b/3,r-2*x/3,n-2*b/3,z_.TOP_LEFT):new fy(i.left+2*x/3,i.top+2*b/3),this.topRightBorderDoubleInnerBox=r>0||n>0?yy(i.left+g,i.top+2*b/3,a-2*w/3,l-2*b/3,z_.TOP_RIGHT):new fy(i.left+i.width-2*w/3,i.top+2*b/3),this.bottomRightBorderDoubleInnerBox=A>0||c>0?yy(i.left+_,i.top+m,A-2*w/3,c-2*B/3,z_.BOTTOM_RIGHT):new fy(i.left+i.width-2*w/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?yy(i.left+2*x/3,i.top+y,d-2*x/3,p-2*B/3,z_.BOTTOM_LEFT):new fy(i.left+2*x/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=r>0||n>0?yy(i.left+x/2,i.top+b/2,r-x/2,n-b/2,z_.TOP_LEFT):new fy(i.left+x/2,i.top+b/2),this.topRightBorderStroke=r>0||n>0?yy(i.left+g,i.top+b/2,a-w/2,l-b/2,z_.TOP_RIGHT):new fy(i.left+i.width-w/2,i.top+b/2),this.bottomRightBorderStroke=A>0||c>0?yy(i.left+_,i.top+m,A-w/2,c-B/2,z_.BOTTOM_RIGHT):new fy(i.left+i.width-w/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?yy(i.left+x/2,i.top+y,d-x/2,p-B/2,z_.BOTTOM_LEFT):new fy(i.left+x/2,i.top+i.height-B/2),this.topLeftBorderBox=r>0||n>0?yy(i.left,i.top,r,n,z_.TOP_LEFT):new fy(i.left,i.top),this.topRightBorderBox=a>0||l>0?yy(i.left+g,i.top,a,l,z_.TOP_RIGHT):new fy(i.left+i.width,i.top),this.bottomRightBorderBox=A>0||c>0?yy(i.left+_,i.top+m,A,c,z_.BOTTOM_RIGHT):new fy(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?yy(i.left,i.top+y,d,p,z_.BOTTOM_LEFT):new fy(i.left,i.top+i.height),this.topLeftPaddingBox=r>0||n>0?yy(i.left+x,i.top+b,Math.max(0,r-x),Math.max(0,n-b),z_.TOP_LEFT):new fy(i.left+x,i.top+b),this.topRightPaddingBox=a>0||l>0?yy(i.left+Math.min(g,i.width-w),i.top+b,g>i.width+w?0:Math.max(0,a-w),Math.max(0,l-b),z_.TOP_RIGHT):new fy(i.left+i.width-w,i.top+b),this.bottomRightPaddingBox=A>0||c>0?yy(i.left+Math.min(_,i.width-x),i.top+Math.min(m,i.height-B),Math.max(0,A-w),Math.max(0,c-B),z_.BOTTOM_RIGHT):new fy(i.left+i.width-w,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?yy(i.left+x,i.top+Math.min(y,i.height-B),Math.max(0,d-x),Math.max(0,p-B),z_.BOTTOM_LEFT):new fy(i.left+x,i.top+i.height-B),this.topLeftContentBox=r>0||n>0?yy(i.left+x+E,i.top+b+P,Math.max(0,r-(x+E)),Math.max(0,n-(b+P)),z_.TOP_LEFT):new fy(i.left+x+E,i.top+b+P),this.topRightContentBox=a>0||l>0?yy(i.left+Math.min(g,i.width+x+E),i.top+b+P,g>i.width+x+E?0:a-x+E,l-(b+P),z_.TOP_RIGHT):new fy(i.left+i.width-(w+C),i.top+b+P),this.bottomRightContentBox=A>0||c>0?yy(i.left+Math.min(_,i.width-(x+E)),i.top+Math.min(m,i.height+b+P),Math.max(0,A-(w+C)),c-(B+M),z_.BOTTOM_RIGHT):new fy(i.left+i.width-(w+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?yy(i.left+x+E,i.top+y,Math.max(0,d-(x+E)),p-(B+M),z_.BOTTOM_LEFT):new fy(i.left+x+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(z_||(z_={}));var yy=function(e,t,i,s,r){var n=(Math.sqrt(2)-1)/3*4,o=i*n,a=s*n,l=e+i,u=t+s;switch(r){case z_.TOP_LEFT:return new gy(new fy(e,u),new fy(e,u-a),new fy(l-o,t),new fy(l,t));case z_.TOP_RIGHT:return new gy(new fy(e,t),new fy(e+o,t),new fy(l,u-a),new fy(l,u));case z_.BOTTOM_RIGHT:return new gy(new fy(l,t),new fy(l,t+a),new fy(e+o,u),new fy(e,u));case z_.BOTTOM_LEFT:default:return new gy(new fy(l,u),new fy(l-o,u),new fy(e,t+a),new fy(e,t))}},by=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},wy=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},By=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},xy=function(e,t){this.path=e,this.target=t,this.type=1},Py=function(e){this.opacity=e,this.type=2,this.target=6},Cy=function(e){return 1===e.type},My=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},Ey=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},Fy=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new _y(this.container),this.container.styles.opacity<1&&this.effects.push(new Py(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,s=this.container.bounds.top+this.container.styles.transformOrigin[1].number,r=this.container.styles.transform;this.effects.push(new By(i,s,r))}if(0!==this.container.styles.overflowX){var n=by(this.curves),o=wy(this.curves);My(n,o)?this.effects.push(new xy(n,6)):(this.effects.push(new xy(n,2)),this.effects.push(new xy(o,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,s=this.effects.slice(0);i;){var r=i.effects.filter((function(e){return!Cy(e)}));if(t||0!==i.container.styles.position||!i.parent){if(s.unshift.apply(s,r),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var n=by(i.curves),o=wy(i.curves);My(n,o)||s.unshift(new xy(o,6))}}else s.unshift.apply(s,r);i=i.parent}return s.filter((function(t){return tm(t.target,e)}))},e}(),ky=function e(t,i,s,r){t.container.elements.forEach((function(n){var o=tm(n.flags,4),a=tm(n.flags,2),l=new Fy(n,t);tm(n.styles.display,2048)&&r.push(l);var u=tm(n.flags,8)?[]:r;if(o||a){var A=o||n.styles.isPositioned()?s:i,c=new Ey(l);if(n.styles.isPositioned()||n.styles.opacity<1||n.styles.isTransformed()){var h=n.styles.zIndex.order;if(h<0){var d=0;A.negativeZIndex.some((function(e,t){return h>e.element.container.styles.zIndex.order?(d=t,!1):d>0})),A.negativeZIndex.splice(d,0,c)}else if(h>0){var p=0;A.positiveZIndex.some((function(e,t){return h>=e.element.container.styles.zIndex.order?(p=t+1,!1):p>0})),A.positiveZIndex.splice(p,0,c)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(c)}else n.styles.isFloating()?A.nonPositionedFloats.push(c):A.nonPositionedInlineLevel.push(c);e(l,c,o?c:s,u)}else n.styles.isInlineLevel()?i.inlineLevel.push(l):i.nonInlineLevel.push(l),e(l,i,s,u);tm(n.flags,8)&&Iy(n,u)}))},Iy=function(e,t){for(var i=e instanceof t_?e.start:1,s=e instanceof t_&&e.reversed,r=0;r0&&e.intrinsicHeight>0){var s=Uy(e),r=wy(t);this.path(r),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,s.left,s.top,s.width,s.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return up(this,void 0,void 0,(function(){var i,s,r,n,o,a,l,u,A,c,h,d,p,f,v,g,m,_;return Ap(this,(function(y){switch(y.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,s=e.curves,r=i.styles,n=0,o=i.textNodes,y.label=1;case 1:return n0&&B>0&&(g=s.ctx.createPattern(p,"repeat"),s.renderRepeat(_,g,P,C))):function(e){return 2===e.type}(i)&&(m=Oy(e,t,[null,null,null]),_=m[0],y=m[1],b=m[2],w=m[3],B=m[4],x=0===i.position.length?[rv]:i.position,P=av(x[0],w),C=av(x[x.length-1],B),M=function(e,t,i,s,r){var n=0,o=0;switch(e.size){case 0:0===e.shape?n=o=Math.min(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(n=Math.min(Math.abs(t),Math.abs(t-s)),o=Math.min(Math.abs(i),Math.abs(i-r)));break;case 2:if(0===e.shape)n=o=Math.min(Ev(t,i),Ev(t,i-r),Ev(t-s,i),Ev(t-s,i-r));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-r))/Math.min(Math.abs(t),Math.abs(t-s)),l=Fv(s,r,t,i,!0),u=l[0],A=l[1];o=a*(n=Ev(u-t,(A-i)/a))}break;case 1:0===e.shape?n=o=Math.max(Math.abs(t),Math.abs(t-s),Math.abs(i),Math.abs(i-r)):1===e.shape&&(n=Math.max(Math.abs(t),Math.abs(t-s)),o=Math.max(Math.abs(i),Math.abs(i-r)));break;case 3:if(0===e.shape)n=o=Math.max(Ev(t,i),Ev(t,i-r),Ev(t-s,i),Ev(t-s,i-r));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-r))/Math.max(Math.abs(t),Math.abs(t-s));var c=Fv(s,r,t,i,!1);u=c[0],A=c[1],o=a*(n=Ev(u-t,(A-i)/a))}}return Array.isArray(e.size)&&(n=av(e.size[0],s),o=2===e.size.length?av(e.size[1],r):n),[n,o]}(i,P,C,w,B),E=M[0],F=M[1],E>0&&F>0&&(k=s.ctx.createRadialGradient(y+P,b+C,0,y+P,b+C,E),Cv(i.stops,2*E).forEach((function(e){return k.addColorStop(e.stop,pv(e.color))})),s.path(_),s.ctx.fillStyle=k,E!==F?(I=e.bounds.left+.5*e.bounds.width,D=e.bounds.top+.5*e.bounds.height,T=1/(S=F/E),s.ctx.save(),s.ctx.translate(I,D),s.ctx.transform(1,0,0,S,0,0),s.ctx.translate(-I,-D),s.ctx.fillRect(y,T*(b-D)+D,w,B*T),s.ctx.restore()):s.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},s=this,r=0,n=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return r0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,2)]:[3,11]:[3,13];case 4:return A.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,3)];case 6:return A.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,n,e.curves)];case 8:return A.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,n,e.curves)];case 10:A.sent(),A.label=11;case 11:n++,A.label=12;case 12:return o++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,s,r){return up(this,void 0,void 0,(function(){var n,o,a,l,u,A,c,h,d,p,f,v,g,m,_,y;return Ap(this,(function(b){return this.ctx.save(),n=function(e,t){switch(t){case 0:return Ty(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return Ty(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return Ty(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return Ty(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(s,i),o=Sy(s,i),2===r&&(this.path(o),this.ctx.clip()),my(o[0])?(a=o[0].start.x,l=o[0].start.y):(a=o[0].x,l=o[0].y),my(o[1])?(u=o[1].end.x,A=o[1].end.y):(u=o[1].x,A=o[1].y),c=0===i||2===i?Math.abs(a-u):Math.abs(l-A),this.ctx.beginPath(),3===r?this.formatPath(n):this.formatPath(o.slice(0,2)),h=t<3?3*t:2*t,d=t<3?2*t:t,3===r&&(h=t,d=t),p=!0,c<=2*h?p=!1:c<=2*h+d?(h*=f=c/(2*h+d),d*=f):(v=Math.floor((c+d)/(h+d)),g=(c-v*h)/(v-1),d=(m=(c-(v+1)*h)/v)<=0||Math.abs(d-g)0&&void 0!==arguments[0]?arguments[0]:{},t=!this._snapshotBegun,i=void 0!==e.width&&void 0!==e.height,s=this.scene.canvas.canvas,r=s.clientWidth,n=s.clientHeight,o=e.width?Math.floor(e.width):s.width,a=e.height?Math.floor(e.height):s.height;i&&(s.width=o,s.height=a),this._snapshotBegun||this.beginSnapshot({width:o,height:a}),e.includeGizmos||this.sendToPlugins("snapshotStarting");for(var l={},u=0,A=this._plugins.length;u0&&void 0!==b[0]?b[0]:{},i=!this._snapshotBegun,s=void 0!==t.width&&void 0!==t.height,r=this.scene.canvas.canvas,n=r.clientWidth,o=r.clientHeight,l=t.width?Math.floor(t.width):r.width,u=t.height?Math.floor(t.height):r.height,s&&(r.width=l,r.height=u),this._snapshotBegun||this.beginSnapshot(),t.includeGizmos||this.sendToPlugins("snapshotStarting"),this.scene._renderer.renderSnapshot(),A=this.scene._renderer.readSnapshotAsCanvas(),s&&(r.width=n,r.height=o,this.scene.glRedraw()),c={},h=[],d=0,p=this._plugins.length;d1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0,s=i||new Set;if(e){if(Bb(e))s.add(e);else if(Bb(e.buffer))s.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"===B(e))for(var r in e)wb(e[r],t,s)}else;return void 0===i?Array.from(s):[]}function Bb(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}var xb=function(){},Pb=function(){function e(t){x(this,e),vb(this,"name",void 0),vb(this,"source",void 0),vb(this,"url",void 0),vb(this,"terminated",!1),vb(this,"worker",void 0),vb(this,"onMessage",void 0),vb(this,"onError",void 0),vb(this,"_loadableURL","");var i=t.name,s=t.source,r=t.url;ub(s||r),this.name=i,this.source=s,this.url=r,this.onMessage=xb,this.onError=function(e){return console.log(e)},this.worker=hb?this._createBrowserWorker():this._createNodeWorker()}return C(e,[{key:"destroy",value:function(){this.onMessage=xb,this.onError=xb,this.worker.terminate(),this.terminated=!0}},{key:"isRunning",get:function(){return Boolean(this.onMessage)}},{key:"postMessage",value:function(e,t){t=t||wb(e),this.worker.postMessage(e,t)}},{key:"_getErrorFromErrorEvent",value:function(e){var t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}},{key:"_createBrowserWorker",value:function(){var e=this;this._loadableURL=yb({source:this.source,url:this.url});var t=new Worker(this._loadableURL,{name:this.name});return t.onmessage=function(t){t.data?e.onMessage(t.data):e.onError(new Error("No data received"))},t.onerror=function(t){e.onError(e._getErrorFromErrorEvent(t)),e.terminated=!0},t.onmessageerror=function(e){return console.error(e)},t}},{key:"_createNodeWorker",value:function(){var e,t=this;if(this.url){var i=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new mb(i,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new mb(this.source,{eval:!0})}return e.on("message",(function(e){t.onMessage(e)})),e.on("error",(function(e){t.onError(e)})),e.on("exit",(function(e){})),e}}],[{key:"isSupported",value:function(){return"undefined"!=typeof Worker&&hb||void 0!==B(mb)}}]),e}(),Cb=function(){function e(t){x(this,e),vb(this,"name","unnamed"),vb(this,"source",void 0),vb(this,"url",void 0),vb(this,"maxConcurrency",1),vb(this,"maxMobileConcurrency",1),vb(this,"onDebug",(function(){})),vb(this,"reuseWorkers",!0),vb(this,"props",{}),vb(this,"jobQueue",[]),vb(this,"idleQueue",[]),vb(this,"count",0),vb(this,"isDestroyed",!1),this.source=t.source,this.url=t.url,this.setProps(t)}var t,i;return C(e,[{key:"destroy",value:function(){this.idleQueue.forEach((function(e){return e.destroy()})),this.isDestroyed=!0}},{key:"setProps",value:function(e){this.props=n(n({},this.props),e),void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}},{key:"startJob",value:(i=u(a().mark((function e(t){var i,s,r,n=this,o=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=o.length>1&&void 0!==o[1]?o[1]:function(e,t,i){return e.done(i)},s=o.length>2&&void 0!==o[2]?o[2]:function(e,t){return e.error(t)},r=new Promise((function(e){return n.jobQueue.push({name:t,onMessage:i,onError:s,onStart:e}),n})),this._startQueuedJob(),e.next=6,r;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"_startQueuedJob",value:(t=u(a().mark((function e(){var t,i,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.jobQueue.length){e.next=2;break}return e.abrupt("return");case 2:if(t=this._getAvailableWorker()){e.next=5;break}return e.abrupt("return");case 5:if(!(i=this.jobQueue.shift())){e.next=18;break}return this.onDebug({message:"Starting job",name:i.name,workerThread:t,backlog:this.jobQueue.length}),s=new gb(i.name,t),t.onMessage=function(e){return i.onMessage(s,e.type,e.payload)},t.onError=function(e){return i.onError(s,e)},i.onStart(s),e.prev=12,e.next=15,s.result;case 15:return e.prev=15,this.returnWorkerToQueue(t),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[12,,15,18]])}))),function(){return t.apply(this,arguments)})},{key:"returnWorkerToQueue",value:function(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}},{key:"_getAvailableWorker",value:function(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count0&&void 0!==arguments[0]?arguments[0]:{};return e._workerFarm=e._workerFarm||new e({}),e._workerFarm.setProps(t),e._workerFarm}}]),e}();vb(Eb,"_workerFarm",void 0);function Fb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t[e.id]||{},s="".concat(e.id,"-worker.js"),r=i.workerUrl;if(r||"compression"!==e.id||(r=t.workerUrl),"test"===t._workerType&&(r="modules/".concat(e.module,"/dist/").concat(s)),!r){var n=e.version;"latest"===n&&(n="latest");var o=n?"@".concat(n):"";r="https://unpkg.com/@loaders.gl/".concat(e.module).concat(o,"/dist/").concat(s)}return ub(r),r}function kb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"3.2.6";ub(e,"no worker provided");var i=e.version;return!(!t||!i)}var Ib=Object.freeze({__proto__:null,default:{}}),Db={};function Sb(e){return Tb.apply(this,arguments)}function Tb(){return Tb=u(a().mark((function e(t){var i,s,r=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=r.length>1&&void 0!==r[1]?r[1]:null,s=r.length>2&&void 0!==r[2]?r[2]:{},i&&(t=Lb(t,i,s)),Db[t]=Db[t]||Rb(t),e.next=6,Db[t];case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)}))),Tb.apply(this,arguments)}function Lb(e,t,i){if(e.startsWith("http"))return e;var s=i.modules||{};return s[e]?s[e]:hb?i.CDN?(ub(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e)):db?"../src/libs/".concat(e):"modules/".concat(t,"/src/libs/").concat(e):"modules/".concat(t,"/dist/libs/").concat(e)}function Rb(e){return Ub.apply(this,arguments)}function Ub(){return(Ub=u(a().mark((function e(t){var i,s,r;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.endsWith("wasm")){e.next=7;break}return e.next=3,fetch(t);case 3:return i=e.sent,e.next=6,i.arrayBuffer();case 6:return e.abrupt("return",e.sent);case 7:if(hb){e.next=20;break}if(e.prev=8,e.t0=Ib&&void 0,!e.t0){e.next=14;break}return e.next=13,(void 0)(t);case 13:e.t0=e.sent;case 14:return e.abrupt("return",e.t0);case 17:return e.prev=17,e.t1=e.catch(8),e.abrupt("return",null);case 20:if(!db){e.next=22;break}return e.abrupt("return",importScripts(t));case 22:return e.next=24,fetch(t);case 24:return s=e.sent,e.next=27,s.text();case 27:return r=e.sent,e.abrupt("return",Ob(r,t));case 29:case"end":return e.stop()}}),e,null,[[8,17]])})))).apply(this,arguments)}function Ob(e,t){if(hb){if(db)return eval.call(cb,e),null;var i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}}function Nb(e,t){return!!Eb.isSupported()&&(!!(hb||null!=t&&t._nodeWorkers)&&(e.worker&&(null==t?void 0:t.worker)))}function Qb(e,t,i,s,r){return Vb.apply(this,arguments)}function Vb(){return Vb=u(a().mark((function e(t,i,s,r,n){var o,l,u,A,c,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.id,l=Fb(t,s),u=Eb.getWorkerFarm(s),A=u.getWorkerPool({name:o,url:l}),s=JSON.parse(JSON.stringify(s)),r=JSON.parse(JSON.stringify(r||{})),e.next=8,A.startJob("process-on-worker",Hb.bind(null,n));case 8:return(c=e.sent).postMessage("process",{input:i,options:s,context:r}),e.next=12,c.result;case 12:return h=e.sent,e.next=15,h.result;case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e)}))),Vb.apply(this,arguments)}function Hb(e,t,i,s){return jb.apply(this,arguments)}function jb(){return(jb=u(a().mark((function e(t,i,s,r){var n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=s,e.next="done"===e.t0?3:"error"===e.t0?5:"process"===e.t0?7:20;break;case 3:return i.done(r),e.abrupt("break",21);case 5:return i.error(new Error(r.error)),e.abrupt("break",21);case 7:return n=r.id,o=r.input,l=r.options,e.prev=8,e.next=11,t(o,l);case 11:u=e.sent,i.postMessage("done",{id:n,result:u}),e.next=19;break;case 15:e.prev=15,e.t1=e.catch(8),A=e.t1 instanceof Error?e.t1.message:"unknown error",i.postMessage("error",{id:n,error:A});case 19:return e.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(s));case 21:case"end":return e.stop()}}),e,null,[[8,15]])})))).apply(this,arguments)}function Gb(e,t,i){if(e.byteLength<=t+i)return"";for(var s=new DataView(e),r="",n=0;n1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return Gb(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){return Gb(e,0,t)}return""}(e),'"'))}}function Wb(e){return e&&"object"===B(e)&&e.isBuffer}function Kb(e){if(Wb(e))return Wb(t=e)?new Uint8Array(t.buffer,t.byteOffset,t.length).slice().buffer:t;var t;if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if("string"==typeof e){var i=e;return(new TextEncoder).encode(i).buffer}if(e&&"object"===B(e)&&e._toArrayBuffer)return e._toArrayBuffer();throw new Error("toArrayBuffer")}function Xb(){for(var e=arguments.length,t=new Array(e),i=0;i=0),ob(t>0),e+(t-1)&~(t-1)}function Zb(e,t,i){var s;if(e instanceof ArrayBuffer)s=new Uint8Array(e);else{var r=e.byteOffset,n=e.byteLength;s=new Uint8Array(e.buffer||e.arrayBuffer,r,n)}return t.set(s,i),i+Jb(s.byteLength,4)}function qb(e){return $b.apply(this,arguments)}function $b(){return($b=u(a().mark((function e(t){var i,s,r,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=[],s=!1,r=!1,e.prev=3,o=I(t);case 5:return e.next=7,o.next();case 7:if(!(s=!(l=e.sent).done)){e.next=13;break}u=l.value,i.push(u);case 10:s=!1,e.next=5;break;case 13:e.next=19;break;case 15:e.prev=15,e.t0=e.catch(3),r=!0,n=e.t0;case 19:if(e.prev=19,e.prev=20,!s||null==o.return){e.next=24;break}return e.next=24,o.return();case 24:if(e.prev=24,!r){e.next=27;break}throw n;case 27:return e.finish(24);case 28:return e.finish(19);case 29:return e.abrupt("return",Xb.apply(void 0,i));case 30:case"end":return e.stop()}}),e,null,[[3,15,19,29],[20,,24,28]])})))).apply(this,arguments)}var ew={};function tw(e){for(var t in ew)if(e.startsWith(t)){var i=ew[t];e=e.replace(t,i)}return e.startsWith("http://")||e.startsWith("https://")||(e="".concat("").concat(e)),e}var iw=function(e){return"function"==typeof e},sw=function(e){return null!==e&&"object"===B(e)},rw=function(e){return sw(e)&&e.constructor==={}.constructor},nw=function(e){return e&&"function"==typeof e[Symbol.iterator]},ow=function(e){return e&&"function"==typeof e[Symbol.asyncIterator]},aw=function(e){return"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json},lw=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},uw=function(e){return function(e){return"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||sw(e)&&iw(e.tee)&&iw(e.cancel)&&iw(e.getReader)}(e)||function(e){return sw(e)&&iw(e.read)&&iw(e.pipe)&&function(e){return"boolean"==typeof e}(e.readable)}(e)},Aw=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,cw=/^([-\w.]+\/[-\w.+]+)/;function hw(e){var t=cw.exec(e);return t?t[1]:e}function dw(e){var t=Aw.exec(e);return t?t[1]:""}var pw=/\?.*/;function fw(e){if(aw(e)){var t=gw(e.url||"");return{url:t,type:hw(e.headers.get("content-type")||"")||dw(t)}}return lw(e)?{url:gw(e.name||""),type:e.type||""}:"string"==typeof e?{url:gw(e),type:dw(e)}:{url:"",type:""}}function vw(e){return aw(e)?e.headers["content-length"]||-1:lw(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}function gw(e){return e.replace(pw,"")}function mw(e){return _w.apply(this,arguments)}function _w(){return(_w=u(a().mark((function e(t){var i,s,r,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!aw(t)){e.next=2;break}return e.abrupt("return",t);case 2:return i={},(s=vw(t))>=0&&(i["content-length"]=String(s)),r=fw(t),n=r.url,(o=r.type)&&(i["content-type"]=o),e.next=9,xw(t);case 9:return(l=e.sent)&&(i["x-first-bytes"]=l),"string"==typeof t&&(t=(new TextEncoder).encode(t)),u=new Response(t,{headers:i}),Object.defineProperty(u,"url",{value:n}),e.abrupt("return",u);case 15:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function yw(e){return bw.apply(this,arguments)}function bw(){return(bw=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.ok){e.next=5;break}return e.next=3,ww(t);case 3:throw i=e.sent,new Error(i);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ww(e){return Bw.apply(this,arguments)}function Bw(){return(Bw=u(a().mark((function e(t){var i,s,r;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i="Failed to fetch resource ".concat(t.url," (").concat(t.status,"): "),e.prev=1,s=t.headers.get("Content-Type"),r=t.statusText,!s.includes("application/json")){e.next=11;break}return e.t0=r,e.t1=" ",e.next=9,t.text();case 9:e.t2=e.sent,r=e.t0+=e.t1.concat.call(e.t1,e.t2);case 11:i=(i+=r).length>60?"".concat(i.slice(0,60),"..."):i,e.next=17;break;case 15:e.prev=15,e.t3=e.catch(1);case 17:return e.abrupt("return",i);case 18:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function xw(e){return Pw.apply(this,arguments)}function Pw(){return(Pw=u(a().mark((function e(t){var i,s,r,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=5,"string"!=typeof t){e.next=3;break}return e.abrupt("return","data:,".concat(t.slice(0,i)));case 3:if(!(t instanceof Blob)){e.next=8;break}return s=t.slice(0,5),e.next=7,new Promise((function(e){var t=new FileReader;t.onload=function(t){var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},t.readAsDataURL(s)}));case 7:return e.abrupt("return",e.sent);case 8:if(!(t instanceof ArrayBuffer)){e.next=12;break}return r=t.slice(0,i),n=Cw(r),e.abrupt("return","data:base64,".concat(n));case 12:return e.abrupt("return",null);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Cw(e){for(var t="",i=new Uint8Array(e),s=0;s=0)}();function Tw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}var Lw=function(){function e(t,i){var s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";x(this,e),this.storage=Tw(s),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function Rw(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(r,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}var Uw={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Ow(e){return"string"==typeof e?Uw[e.toUpperCase()]||Uw.WHITE:e}function Nw(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],s=Object.getPrototypeOf(e),r=Object.getOwnPropertyNames(s),n=c(r);try{var o=function(){var s=t.value;"function"==typeof e[s]&&(i.find((function(e){return s===e}))||(e[s]=e[s].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function Qw(e,t){if(!e)throw new Error(t||"Assertion failed")}function Vw(){var e;if(Sw&&kw.performance)e=kw.performance.now();else if(Iw.hrtime){var t=Iw.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}var Hw={debug:Sw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},jw={enabled:!0,level:0};function Gw(){}var zw={},Ww={once:!0};function Kw(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}var Xw=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;x(this,e),this.id=i,this.VERSION=Dw,this._startTs=Vw(),this._deltaTs=Vw(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Lw("__probe-".concat(this.id,"__"),jw),this.userData={},this.timeStamp("".concat(this.id," started")),Nw(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((Vw()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((Vw()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"assert",value:function(e,t){Qw(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,Hw.warn,arguments,Ww)}},{key:"error",value:function(e){return this._getLogFunction(0,e,Hw.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,Hw.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,Hw.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){return this._getLogFunction(e,t,Hw.debug||Hw.info,arguments,Ww)}},{key:"table",value:function(e,t,i){return t?this._getLogFunction(e,t,console.table||Gw,i&&[i],{tag:Kw(t)}):Gw}},{key:"image",value:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){var t=e.logLevel,i=e.priority,s=e.image,r=e.message,n=void 0===r?"":r,o=e.scale,a=void 0===o?1:o;return this._shouldLog(t||i)?Sw?function(e){var t=e.image,i=e.message,s=void 0===i?"":i,r=e.scale,n=void 0===r?1:r;if("string"==typeof t){var o=new Image;return o.onload=function(){var e,t=Rw(o,s,n);(e=console).log.apply(e,A(t))},o.src=t,Gw}var a=t.nodeName||"";if("img"===a.toLowerCase()){var l;return(l=console).log.apply(l,A(Rw(t,s,n))),Gw}if("canvas"===a.toLowerCase()){var u=new Image;return u.onload=function(){var e;return(e=console).log.apply(e,A(Rw(u,s,n)))},u.src=t.toDataURL(),Gw}return Gw}({image:s,message:n,scale:a}):function(e){var t=e.image,i=(e.message,e.scale),s=void 0===i?1:i,r=null;try{r=module.require("asciify-image")}catch(e){}if(r)return function(){return r(t,{fit:"box",width:"".concat(Math.round(80*s),"%")}).then((function(e){return console.log(e)}))};return Gw}({image:s,message:n,scale:a}):Gw}))},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"time",value:function(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}},{key:"timeEnd",value:function(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}},{key:"timeStamp",value:function(e,t){return this._getLogFunction(e,t,console.timeStamp||Gw)}},{key:"group",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},s=i=Jw({logLevel:e,message:t,opts:i}),r=s.collapsed;return i.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||Gw)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=Yw(e)}},{key:"_getLogFunction",value:function(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],r=arguments.length>4?arguments[4]:void 0;if(this._shouldLog(e)){var n;r=Jw({logLevel:e,message:t,args:s,opts:r}),Qw(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=Vw();var o=r.tag||r.message;if(r.once){if(zw[o])return Gw;zw[o]=Vw()}return t=Zw(this.id,r.message,r),(n=i).bind.apply(n,[console,t].concat(A(r.args)))}return Gw}}]),e}();function Yw(e){if(!e)return 0;var t;switch(B(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Qw(Number.isFinite(t)&&t>=0),t}function Jw(e){var t=e.logLevel,i=e.message;e.logLevel=Yw(t);for(var s=e.args?Array.from(e.args):[];s.length&&s.shift()!==i;);switch(e.args=s,B(t)){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var r=B(e.message);return Qw("string"===r||"object"===r),Object.assign(e,e.opts)}function Zw(e,t,i){if("string"==typeof t){var s=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((r=i.total)<10?"".concat(r.toFixed(2),"ms"):r<100?"".concat(r.toFixed(1),"ms"):r<1e3?"".concat(r.toFixed(0),"ms"):"".concat((r/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Sw||"string"!=typeof e||(t&&(t=Ow(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Ow(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var r;return t}Xw.VERSION=Dw;var qw=new Xw({id:"loaders.gl"}),$w=function(){function e(){x(this,e)}return C(e,[{key:"log",value:function(){return function(){}}},{key:"info",value:function(){return function(){}}},{key:"warn",value:function(){return function(){}}},{key:"error",value:function(){return function(){}}}]),e}(),eB={fetch:null,mimeType:void 0,nothrow:!1,log:new(function(){function e(){x(this,e),vb(this,"console",void 0),this.console=console}return C(e,[{key:"log",value:function(){for(var e,t=arguments.length,i=new Array(t),s=0;s=0)}()}var dB={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"===("undefined"==typeof process?"undefined":B(process))&&process},pB=dB.window||dB.self||dB.global,fB=dB.process||{},vB="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";function gB(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}hB();var mB,_B=function(){function e(t){x(this,e);var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";vb(this,"storage",void 0),vb(this,"id",void 0),vb(this,"config",{}),this.storage=gB(s),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function yB(e,t,i){var s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,r=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>s&&(i=Math.min(i,s/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(r,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}function bB(e){return"string"==typeof e?mB[e.toUpperCase()]||mB.WHITE:e}function wB(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],s=Object.getPrototypeOf(e),r=Object.getOwnPropertyNames(s),n=c(r);try{var o=function(){var s=t.value;"function"==typeof e[s]&&(i.find((function(e){return s===e}))||(e[s]=e[s].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function BB(e,t){if(!e)throw new Error(t||"Assertion failed")}function xB(){var e,t,i;if(hB&&"performance"in pB)e=null==pB||null===(t=pB.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in fB){var s,r=null==fB||null===(s=fB.hrtime)||void 0===s?void 0:s.call(fB);e=1e3*r[0]+r[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(mB||(mB={}));var PB={debug:hB&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},CB={enabled:!0,level:0};function MB(){}var EB={},FB={once:!0},kB=function(){function e(){x(this,e);var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;vb(this,"id",void 0),vb(this,"VERSION",vB),vb(this,"_startTs",xB()),vb(this,"_deltaTs",xB()),vb(this,"_storage",void 0),vb(this,"userData",{}),vb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=i,this._storage=new _B("__probe-".concat(this.id,"__"),CB),this.userData={},this.timeStamp("".concat(this.id," started")),wB(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((xB()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((xB()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"assert",value:function(e,t){BB(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,PB.warn,arguments,FB)}},{key:"error",value:function(e){return this._getLogFunction(0,e,PB.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,PB.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,PB.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){for(var i=arguments.length,s=new Array(i>2?i-2:0),r=2;r2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},s=DB({logLevel:e,message:t,opts:i}),r=i.collapsed;return s.method=(r?console.groupCollapsed:console.group)||console.info,this._getLogFunction(s)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||MB)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=IB(e)}},{key:"_getLogFunction",value:function(e,t,i,s,r){if(this._shouldLog(e)){var n;r=DB({logLevel:e,message:t,args:s,opts:r}),BB(i=i||r.method),r.total=this.getTotal(),r.delta=this.getDelta(),this._deltaTs=xB();var o=r.tag||r.message;if(r.once){if(EB[o])return MB;EB[o]=xB()}return t=function(e,t,i){if("string"==typeof t){var s=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((r=i.total)<10?"".concat(r.toFixed(2),"ms"):r<100?"".concat(r.toFixed(1),"ms"):r<1e3?"".concat(r.toFixed(0),"ms"):"".concat((r/1e3).toFixed(2),"s")):"";t=function(e,t,i){return hB||"string"!=typeof e||(t&&(t=bB(t),e="[".concat(t,"m").concat(e,"")),i&&(t=bB(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(s," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var r;return t}(this.id,r.message,r),(n=i).bind.apply(n,[console,t].concat(A(r.args)))}return MB}}]),e}();function IB(e){if(!e)return 0;var t;switch(B(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return BB(Number.isFinite(t)&&t>=0),t}function DB(e){var t=e.logLevel,i=e.message;e.logLevel=IB(t);for(var s=e.args?Array.from(e.args):[];s.length&&s.shift()!==i;);switch(B(t)){case"string":case"function":void 0!==i&&s.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var r=B(e.message);return BB("string"===r||"object"===r),Object.assign(e,{args:s},e.opts)}function SB(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}vb(kB,"VERSION",vB);var TB=new kB({id:"loaders.gl"}),LB=/\.([^.]+)$/;function RB(e){return UB.apply(this,arguments)}function UB(){return UB=u(a().mark((function e(t){var i,s,r,o,l=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=l.length>1&&void 0!==l[1]?l[1]:[],s=l.length>2?l[2]:void 0,r=l.length>3?l[3]:void 0,QB(t)){e.next=5;break}return e.abrupt("return",null);case 5:if(!(o=OB(t,i,n(n({},s),{},{nothrow:!0}),r))){e.next=8;break}return e.abrupt("return",o);case 8:if(!lw(t)){e.next=13;break}return e.next=11,t.slice(0,10).arrayBuffer();case 11:t=e.sent,o=OB(t,i,s,r);case 13:if(o||null!=s&&s.nothrow){e.next=15;break}throw new Error(VB(t));case 15:return e.abrupt("return",o);case 16:case"end":return e.stop()}}),e)}))),UB.apply(this,arguments)}function OB(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,s=arguments.length>3?arguments[3]:void 0;if(!QB(e))return null;if(t&&!Array.isArray(t))return AB(t);var r,n=[];(t&&(n=n.concat(t)),null!=i&&i.ignoreRegisteredLoaders)||(r=n).push.apply(r,A(cB()));HB(n);var o=NB(e,n,i,s);if(!(o||null!=i&&i.nothrow))throw new Error(VB(e));return o}function NB(e,t,i,s){var r,n=fw(e),o=n.url,a=n.type,l=o||(null==s?void 0:s.url),u=null,A="";(null!=i&&i.mimeType&&(u=jB(t,null==i?void 0:i.mimeType),A="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType)),u=u||function(e,t){var i=t&&LB.exec(t),s=i&&i[1];return s?function(e,t){t=t.toLowerCase();var i,s=c(e);try{for(s.s();!(i=s.n()).done;){var r,n=i.value,o=c(n.extensions);try{for(o.s();!(r=o.n()).done;){if(r.value.toLowerCase()===t)return n}}catch(e){o.e(e)}finally{o.f()}}}catch(e){s.e(e)}finally{s.f()}return null}(e,s):null}(t,l),A=A||(u?"matched url ".concat(l):""),u=u||jB(t,a),A=A||(u?"matched MIME type ".concat(a):""),u=u||function(e,t){if(!t)return null;var i,s=c(e);try{for(s.s();!(i=s.n()).done;){var r=i.value;if("string"==typeof t){if(GB(t,r))return r}else if(ArrayBuffer.isView(t)){if(zB(t.buffer,t.byteOffset,r))return r}else if(t instanceof ArrayBuffer){if(zB(t,0,r))return r}}}catch(e){s.e(e)}finally{s.f()}return null}(t,e),A=A||(u?"matched initial data ".concat(WB(e)):""),u=u||jB(t,null==i?void 0:i.fallbackMimeType),A=A||(u?"matched fallback MIME type ".concat(a):""))&&TB.log(1,"selectLoader selected ".concat(null===(r=u)||void 0===r?void 0:r.name,": ").concat(A,"."));return u}function QB(e){return!(e instanceof Response&&204===e.status)}function VB(e){var t=fw(e),i=t.url,s=t.type,r="No valid loader found (";r+=i?"".concat(function(e){var t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(i),", "):"no url provided, ",r+="MIME type: ".concat(s?'"'.concat(s,'"'):"not provided",", ");var n=e?WB(e):"";return r+=n?' first bytes: "'.concat(n,'"'):"first bytes: not available",r+=")"}function HB(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){AB(t.value)}}catch(e){i.e(e)}finally{i.f()}}function jB(e,t){var i,s=c(e);try{for(s.s();!(i=s.n()).done;){var r=i.value;if(r.mimeTypes&&r.mimeTypes.includes(t))return r;if(t==="application/x.".concat(r.id))return r}}catch(e){s.e(e)}finally{s.f()}return null}function GB(e,t){return t.testText?t.testText(e):(Array.isArray(t.tests)?t.tests:[t.tests]).some((function(t){return e.startsWith(t)}))}function zB(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((function(s){return function(e,t,i,s){if(s instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return KB(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){var i=0;return KB(e,i,t)}return""}function KB(e,t,i){if(e.byteLength1&&void 0!==A[1]?A[1]:{},s=t.chunkSize,r=void 0===s?262144:s,n=0;case 3:if(!(n2&&void 0!==arguments[2]?arguments[2]:null;if(i)return i;var s=n({fetch:nB(t,e)},e);return Array.isArray(s.loaders)||(s.loaders=null),s}function ox(e,t){if(!t&&e&&!Array.isArray(e))return e;var i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){var s=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[].concat(A(i),A(s)):s}return i&&i.length?i:null}function ax(e,t,i,s){return lx.apply(this,arguments)}function lx(){return(lx=u(a().mark((function e(t,i,s,r){var n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return ub(!r||"object"===B(r)),!i||Array.isArray(i)||uB(i)||(r=void 0,s=i,i=void 0),e.next=4,t;case 4:return t=e.sent,s=s||{},n=fw(t),o=n.url,l=ox(i,r),e.next=11,RB(t,l,s);case 11:if(u=e.sent){e.next=14;break}return e.abrupt("return",null);case 14:return s=rB(s,u,l,o),r=nx({url:o,parse:ax,loaders:l},s,r),e.next=18,ux(u,t,s,r);case 18:return e.abrupt("return",e.sent);case 19:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ux(e,t,i,s){return Ax.apply(this,arguments)}function Ax(){return(Ax=u(a().mark((function e(t,i,s,r){var n,o,l,u,A,c,h,d;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return kb(t),aw(i)&&(o=(n=i).ok,l=n.redirected,u=n.status,A=n.statusText,c=n.type,h=n.url,d=Object.fromEntries(n.headers.entries()),r.response={headers:d,ok:o,redirected:l,status:u,statusText:A,type:c,url:h}),e.next=4,sx(i,t,s);case 4:if(i=e.sent,!t.parseTextSync||"string"!=typeof i){e.next=8;break}return s.dataType="text",e.abrupt("return",t.parseTextSync(i,s,r,t));case 8:if(!Nb(t,s)){e.next=12;break}return e.next=11,Qb(t,i,s,r,ax);case 11:case 15:case 19:return e.abrupt("return",e.sent);case 12:if(!t.parseText||"string"!=typeof i){e.next=16;break}return e.next=15,t.parseText(i,s,r,t);case 16:if(!t.parse){e.next=20;break}return e.next=19,t.parse(i,s,r,t);case 20:throw ub(!t.parseSync),new Error("".concat(t.id," loader - no parser found and worker is disabled"));case 22:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var cx,hx,dx="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),px="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");function fx(e){return vx.apply(this,arguments)}function vx(){return(vx=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basis){e.next=3;break}return e.abrupt("return",i.basis);case 3:return cx=cx||gx(t),e.next=6,cx;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function gx(e){return mx.apply(this,arguments)}function mx(){return(mx=u(a().mark((function e(t){var i,s,r,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,s=null,e.t0=Promise,e.next=5,Sb("basis_transcoder.js","textures",t);case 5:return e.t1=e.sent,e.next=8,Sb("basis_transcoder.wasm","textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return r=e.sent,n=h(r,2),i=n[0],s=n[1],i=i||globalThis.BASIS,e.next=19,_x(i,s);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function _x(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile;(0,e.initializeBasis)(),t({BasisFile:i})}))}))}function yx(e){return bx.apply(this,arguments)}function bx(){return(bx=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basisEncoder){e.next=3;break}return e.abrupt("return",i.basisEncoder);case 3:return hx=hx||wx(t),e.next=6,hx;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function wx(e){return Bx.apply(this,arguments)}function Bx(){return(Bx=u(a().mark((function e(t){var i,s,r,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,s=null,e.t0=Promise,e.next=5,Sb(px,"textures",t);case 5:return e.t1=e.sent,e.next=8,Sb(dx,"textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return r=e.sent,n=h(r,2),i=n[0],s=n[1],i=i||globalThis.BASIS,e.next=19,xx(i,s);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function xx(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile,s=e.KTX2File,r=e.initializeBasis,n=e.BasisEncoder;r(),t({BasisFile:i,KTX2File:s,BasisEncoder:n})}))}))}var Px,Cx,Mx,Ex,Fx,kx,Ix,Dx,Sx,Tx=33776,Lx=33779,Rx=35840,Ux=35842,Ox=36196,Nx=37808,Qx=["","WEBKIT_","MOZ_"],Vx={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"},Hx=null;function jx(e){if(!Hx){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,Hx=new Set;var t,i=c(Qx);try{for(i.s();!(t=i.n()).done;){var s=t.value;for(var r in Vx)if(e&&e.getExtension("".concat(s).concat(r))){var n=Vx[r];Hx.add(n)}}}catch(e){i.e(e)}finally{i.f()}}return Hx}(Sx=Px||(Px={}))[Sx.NONE=0]="NONE",Sx[Sx.BASISLZ=1]="BASISLZ",Sx[Sx.ZSTD=2]="ZSTD",Sx[Sx.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(Cx||(Cx={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(Mx||(Mx={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(Ex||(Ex={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(Fx||(Fx={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(kx||(kx={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(Ix||(Ix={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(Dx||(Dx={}));var Gx=[171,75,84,88,32,50,48,187,13,10,26,10];function zx(e){var t=new Uint8Array(e);return!(t.byteLength1&&void 0!==s[1]?s[1]:null)&&mP||(i=null),!i){e.next=13;break}return e.prev=3,e.next=6,createImageBitmap(t,i);case 6:return e.abrupt("return",e.sent);case 9:e.prev=9,e.t0=e.catch(3),console.warn(e.t0),mP=!1;case 13:return e.next=15,createImageBitmap(t);case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e,null,[[3,9]])}))),wP.apply(this,arguments)}function BP(e){for(var t in e||gP)return!1;return!0}function xP(e){var t=PP(e);return function(e){var t=PP(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){var t=PP(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;var i=function(){for(var e=new Set([65499,65476,65484,65501,65534]),t=65504;t<65520;++t)e.add(t);var i=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:i}}(),s=i.tableMarkers,r=i.sofMarkers,n=2;for(;n+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){var t=PP(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function PP(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}function CP(e,t){return MP.apply(this,arguments)}function MP(){return MP=u(a().mark((function e(t,i){var s,r,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return s=xP(t)||{},r=s.mimeType,ob(n=globalThis._parseImageNode),e.next=5,n(t,r);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e)}))),MP.apply(this,arguments)}function EP(){return(EP=u(a().mark((function e(t,i,s){var r,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=(i=i||{}).image||{},n=r.type||"auto",o=(s||{}).url,l=FP(n),e.t0=l,e.next="imagebitmap"===e.t0?8:"image"===e.t0?12:"data"===e.t0?16:20;break;case 8:return e.next=10,_P(t,i,o);case 10:return u=e.sent,e.abrupt("break",21);case 12:return e.next=14,dP(t,i,o);case 14:return u=e.sent,e.abrupt("break",21);case 16:return e.next=18,CP(t);case 18:return u=e.sent,e.abrupt("break",21);case 20:ob(!1);case 21:return"data"===n&&(u=aP(u)),e.abrupt("return",u);case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function FP(e){switch(e){case"auto":case"data":return function(){if(sP)return"imagebitmap";if(iP)return"image";if(nP)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return sP||iP||nP;case"imagebitmap":return sP;case"image":return iP;case"data":return nP;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}var kP={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:function(e,t,i){return EP.apply(this,arguments)},tests:[function(e){return Boolean(xP(new DataView(e)))}],options:{image:{type:"auto",decode:!0}}},IP=["image/png","image/jpeg","image/gif"],DP={};function SP(e){return void 0===DP[e]&&(DP[e]=function(e){switch(e){case"image/webp":return function(){if(!ab)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch(e){return!1}}();case"image/svg":return ab;default:if(!ab){var t=globalThis._parseImageNode;return Boolean(t)&&IP.includes(e)}return!0}}(e)),DP[e]}function TP(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function LP(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;var i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}function RP(e,t,i){var s=e.bufferViews[i];TP(s);var r=t[s.buffer];TP(r);var n=(s.byteOffset||0)+r.byteOffset;return new Uint8Array(r.arrayBuffer,n,s.byteLength)}var UP=["SCALAR","VEC2","VEC3","VEC4"],OP=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],NP=new Map(OP),QP={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},VP={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},HP={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function jP(e){return UP[e-1]||UP[0]}function GP(e){var t=NP.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function zP(e,t){var i=HP[e.componentType],s=QP[e.type],r=VP[e.componentType],n=e.count*s,o=e.count*s*r;return TP(o>=0&&o<=t.byteLength),{ArrayType:i,length:n,byteLength:o}}var WP,KP={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]},XP=function(){function e(t){x(this,e),vb(this,"gltf",void 0),vb(this,"sourceBuffers",void 0),vb(this,"byteLength",void 0),this.gltf=t||{json:n({},KP),buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}return C(e,[{key:"json",get:function(){return this.gltf.json}},{key:"getApplicationData",value:function(e){return this.json[e]}},{key:"getExtraData",value:function(e){return(this.json.extras||{})[e]}},{key:"getExtension",value:function(e){var t=this.getUsedExtensions().find((function(t){return t===e})),i=this.json.extensions||{};return t?i[e]||!0:null}},{key:"getRequiredExtension",value:function(e){var t=this.getRequiredExtensions().find((function(t){return t===e}));return t?this.getExtension(e):null}},{key:"getRequiredExtensions",value:function(){return this.json.extensionsRequired||[]}},{key:"getUsedExtensions",value:function(){return this.json.extensionsUsed||[]}},{key:"getObjectExtension",value:function(e,t){return(e.extensions||{})[t]}},{key:"getScene",value:function(e){return this.getObject("scenes",e)}},{key:"getNode",value:function(e){return this.getObject("nodes",e)}},{key:"getSkin",value:function(e){return this.getObject("skins",e)}},{key:"getMesh",value:function(e){return this.getObject("meshes",e)}},{key:"getMaterial",value:function(e){return this.getObject("materials",e)}},{key:"getAccessor",value:function(e){return this.getObject("accessors",e)}},{key:"getTexture",value:function(e){return this.getObject("textures",e)}},{key:"getSampler",value:function(e){return this.getObject("samplers",e)}},{key:"getImage",value:function(e){return this.getObject("images",e)}},{key:"getBufferView",value:function(e){return this.getObject("bufferViews",e)}},{key:"getBuffer",value:function(e){return this.getObject("buffers",e)}},{key:"getObject",value:function(e,t){if("object"===B(t))return t;var i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}},{key:"getTypedArrayForBufferView",value:function(e){var t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];TP(i);var s=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,s,e.byteLength)}},{key:"getTypedArrayForAccessor",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=zP(e,t),r=s.ArrayType,n=s.length;return new r(i,t.byteOffset+e.byteOffset,n)}},{key:"getTypedArrayForImageData",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,s=t.byteOffset||0;return new Uint8Array(i,s,t.byteLength)}},{key:"addApplicationData",value:function(e,t){return this.json[e]=t,this}},{key:"addExtraData",value:function(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}},{key:"addObjectExtension",value:function(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}},{key:"setObjectExtension",value:function(e,t,i){(e.extensions||{})[t]=i}},{key:"removeObjectExtension",value:function(e,t){var i=e.extensions||{},s=i[t];return delete i[t],s}},{key:"addExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return TP(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}},{key:"addRequiredExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return TP(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}},{key:"registerUsedExtension",value:function(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((function(t){return t===e}))||this.json.extensionsUsed.push(e)}},{key:"registerRequiredExtension",value:function(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((function(t){return t===e}))||this.json.extensionsRequired.push(e)}},{key:"removeExtension",value:function(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}},{key:"setDefaultScene",value:function(e){this.json.scene=e}},{key:"addScene",value:function(e){var t=e.nodeIndices;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}},{key:"addNode",value:function(e){var t=e.meshIndex,i=e.matrix;this.json.nodes=this.json.nodes||[];var s={mesh:t};return i&&(s.matrix=i),this.json.nodes.push(s),this.json.nodes.length-1}},{key:"addMesh",value:function(e){var t=e.attributes,i=e.indices,s=e.material,r=e.mode,n=void 0===r?4:r,o={primitives:[{attributes:this._addAttributes(t),mode:n}]};if(i){var a=this._addIndices(i);o.primitives[0].indices=a}return Number.isFinite(s)&&(o.primitives[0].material=s),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}},{key:"addPointCloud",value:function(e){var t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}},{key:"addImage",value:function(e,t){var i=xP(e),s=t||(null==i?void 0:i.mimeType),r={bufferView:this.addBufferView(e),mimeType:s};return this.json.images=this.json.images||[],this.json.images.push(r),this.json.images.length-1}},{key:"addBufferView",value:function(e){var t=e.byteLength;TP(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);var i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=Jb(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}},{key:"addAccessor",value:function(e,t){var i={bufferView:e,type:jP(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}},{key:"addBinaryBuffer",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{size:3},i=this.addBufferView(e),s={min:t.min,max:t.max};s.min&&s.max||(s=this._getAccessorMinMax(e,t.size));var r={size:t.size,componentType:GP(e),count:Math.round(e.length/t.size),min:s.min,max:s.max};return this.addAccessor(i,Object.assign(r,t))}},{key:"addTexture",value:function(e){var t={source:e.imageIndex};return this.json.textures=this.json.textures||[],this.json.textures.push(t),this.json.textures.length-1}},{key:"addMaterial",value:function(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}},{key:"createBinaryChunk",value:function(){var e,t;this.gltf.buffers=[];var i,s=this.byteLength,r=new ArrayBuffer(s),n=new Uint8Array(r),o=0,a=c(this.sourceBuffers||[]);try{for(a.s();!(i=a.n()).done;){o=Zb(i.value,n,o)}}catch(e){a.e(e)}finally{a.f()}null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=s:this.json.buffers=[{byteLength:s}],this.gltf.binary=r,this.sourceBuffers=[r]}},{key:"_removeStringFromArray",value:function(e,t){for(var i=!0;i;){var s=e.indexOf(t);s>-1?e.splice(s,1):i=!1}}},{key:"_addAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};for(var i in e){var s=e[i],r=this._getGltfAttributeName(i),n=this.addBinaryBuffer(s.value,s);t[r]=n}return t}},{key:"_addIndices",value:function(e){return this.addBinaryBuffer(e,{size:1})}},{key:"_getGltfAttributeName",value:function(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}},{key:"_getAccessorMinMax",value:function(e,t){var i={min:null,max:null};if(e.length5&&void 0!==u[5]?u[5]:"NONE",e.next=3,sC();case 3:lC(l=e.sent,l.exports[eC[n]],t,i,s,r,l.exports[$P[o||"NONE"]]);case 5:case"end":return e.stop()}}),e)}))),iC.apply(this,arguments)}function sC(){return rC.apply(this,arguments)}function rC(){return(rC=u(a().mark((function e(){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return WP||(WP=nC()),e.abrupt("return",WP);case 2:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function nC(){return oC.apply(this,arguments)}function oC(){return(oC=u(a().mark((function e(){var t,i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=YP,WebAssembly.validate(ZP)&&(t=JP,console.log("Warning: meshopt_decoder is using experimental SIMD support")),e.next=4,WebAssembly.instantiate(aC(t),{});case 4:return i=e.sent,e.next=7,i.instance.exports.__wasm_call_ctors();case 7:return e.abrupt("return",i.instance);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function aC(e){for(var t=new Uint8Array(e.length),i=0;i96?s-71:s>64?s-65:s>47?s+4:s>46?63:62}for(var r=0,n=0;nr?A:r,n=c>n?c:n,o=h>o?h:o}return[[t,i,s],[r,n,o]]}var gC=function(){function e(t,i){x(this,e),vb(this,"fields",void 0),vb(this,"metadata",void 0),function(e,t){if(!e)throw new Error(t||"loader assertion failed.")}(Array.isArray(t)),function(e){var t,i={},s=c(e);try{for(s.s();!(t=s.n()).done;){var r=t.value;i[r.name]&&console.warn("Schema: duplicated field name",r.name,r),i[r.name]=!0}}catch(e){s.e(e)}finally{s.f()}}(t),this.fields=t,this.metadata=i||new Map}return C(e,[{key:"compareTo",value:function(e){if(this.metadata!==e.metadata)return!1;if(this.fields.length!==e.fields.length)return!1;for(var t=0;t2&&void 0!==arguments[2]&&arguments[2],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:new Map;x(this,e),vb(this,"name",void 0),vb(this,"type",void 0),vb(this,"nullable",void 0),vb(this,"metadata",void 0),this.name=t,this.type=i,this.nullable=s,this.metadata=r}return C(e,[{key:"typeId",get:function(){return this.type&&this.type.typeId}},{key:"clone",value:function(){return new e(this.name,this.type,this.nullable,this.metadata)}},{key:"compareTo",value:function(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}},{key:"toString",value:function(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}]),e}();!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(_C||(_C={}));var bC=function(){function e(){x(this,e)}return C(e,[{key:"typeId",get:function(){return _C.NONE}},{key:"compareTo",value:function(e){return this===e}}],[{key:"isNull",value:function(e){return e&&e.typeId===_C.Null}},{key:"isInt",value:function(e){return e&&e.typeId===_C.Int}},{key:"isFloat",value:function(e){return e&&e.typeId===_C.Float}},{key:"isBinary",value:function(e){return e&&e.typeId===_C.Binary}},{key:"isUtf8",value:function(e){return e&&e.typeId===_C.Utf8}},{key:"isBool",value:function(e){return e&&e.typeId===_C.Bool}},{key:"isDecimal",value:function(e){return e&&e.typeId===_C.Decimal}},{key:"isDate",value:function(e){return e&&e.typeId===_C.Date}},{key:"isTime",value:function(e){return e&&e.typeId===_C.Time}},{key:"isTimestamp",value:function(e){return e&&e.typeId===_C.Timestamp}},{key:"isInterval",value:function(e){return e&&e.typeId===_C.Interval}},{key:"isList",value:function(e){return e&&e.typeId===_C.List}},{key:"isStruct",value:function(e){return e&&e.typeId===_C.Struct}},{key:"isUnion",value:function(e){return e&&e.typeId===_C.Union}},{key:"isFixedSizeBinary",value:function(e){return e&&e.typeId===_C.FixedSizeBinary}},{key:"isFixedSizeList",value:function(e){return e&&e.typeId===_C.FixedSizeList}},{key:"isMap",value:function(e){return e&&e.typeId===_C.Map}},{key:"isDictionary",value:function(e){return e&&e.typeId===_C.Dictionary}}]),e}(),wC=function(e,t){g(s,bC);var i=_(s);function s(e,t){var r;return x(this,s),vb(b(r=i.call(this)),"isSigned",void 0),vb(b(r),"bitWidth",void 0),r.isSigned=e,r.bitWidth=t,r}return C(s,[{key:"typeId",get:function(){return _C.Int}},{key:t,get:function(){return"Int"}},{key:"toString",value:function(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}]),s}(0,Symbol.toStringTag),BC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,8)}return C(i)}(),xC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,16)}return C(i)}(),PC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,32)}return C(i)}(),CC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,8)}return C(i)}(),MC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,16)}return C(i)}(),EC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,32)}return C(i)}(),FC=32,kC=64,IC=function(e,t){g(s,bC);var i=_(s);function s(e){var t;return x(this,s),vb(b(t=i.call(this)),"precision",void 0),t.precision=e,t}return C(s,[{key:"typeId",get:function(){return _C.Float}},{key:t,get:function(){return"Float"}},{key:"toString",value:function(){return"Float".concat(this.precision)}}]),s}(0,Symbol.toStringTag),DC=function(e){g(i,IC);var t=_(i);function i(){return x(this,i),t.call(this,FC)}return C(i)}(),SC=function(e){g(i,IC);var t=_(i);function i(){return x(this,i),t.call(this,kC)}return C(i)}(),TC=function(e,t){g(s,bC);var i=_(s);function s(e,t){var r;return x(this,s),vb(b(r=i.call(this)),"listSize",void 0),vb(b(r),"children",void 0),r.listSize=e,r.children=[t],r}return C(s,[{key:"typeId",get:function(){return _C.FixedSizeList}},{key:"valueType",get:function(){return this.children[0].type}},{key:"valueField",get:function(){return this.children[0]}},{key:t,get:function(){return"FixedSizeList"}},{key:"toString",value:function(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}]),s}(0,Symbol.toStringTag);function LC(e,t,i){var s=function(e){switch(e.constructor){case Int8Array:return new BC;case Uint8Array:return new CC;case Int16Array:return new xC;case Uint16Array:return new MC;case Int32Array:return new PC;case Uint32Array:return new EC;case Float32Array:return new DC;case Float64Array:return new SC;default:throw new Error("array type not supported")}}(t.value),r=i||function(e){var t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new yC(e,new TC(t.size,new yC("value",s)),!1,r)}function RC(e,t,i){var s=OC(t.metadata),r=[],n=function(e){var t={};for(var i in e){var s=e[i];t[s.name||"undefined"]=s}return t}(t.attributes);for(var o in e){var a=UC(o,e[o],n[o]);r.push(a)}if(i){var l=UC("indices",i);r.push(l)}return new gC(r,s)}function UC(e,t,i){return LC(e,t,i?OC(i.metadata):void 0)}function OC(e){var t=new Map;for(var i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}var NC={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},QC={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},VC=function(){function e(t){x(this,e),vb(this,"draco",void 0),vb(this,"decoder",void 0),vb(this,"metadataQuerier",void 0),this.draco=t,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}return C(e,[{key:"destroy",value:function(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}},{key:"parseSync",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);var s=this.decoder.GetEncodedGeometryType(i),r=s===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{var o;switch(s){case this.draco.TRIANGULAR_MESH:o=this.decoder.DecodeBufferToMesh(i,r);break;case this.draco.POINT_CLOUD:o=this.decoder.DecodeBufferToPointCloud(i,r);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!o.ok()||!r.ptr){var a="DRACO decompression failed: ".concat(o.error_msg());throw new Error(a)}var l=this._getDracoLoaderData(r,s,t),u=this._getMeshData(r,l,t),A=vC(u.attributes),c=RC(u.attributes,l,u.indices),h=n(n({loader:"draco",loaderData:l,header:{vertexCount:r.num_points(),boundingBox:A}},u),{},{schema:c});return h}finally{this.draco.destroy(i),r&&this.draco.destroy(r)}}},{key:"_getDracoLoaderData",value:function(e,t,i){var s=this._getTopLevelMetadata(e),r=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:s,attributes:r}}},{key:"_getDracoAttributes",value:function(e,t){for(var i={},s=0;s2&&void 0!==arguments[2]&&arguments[2];if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),s=t.length/i);return{buffer:t,size:i,count:s}}(e),i=t.buffer,s=t.size;return{value:i,size:s,byteOffset:0,count:t.count,type:jP(s),componentType:GP(i)}}function tM(){return(tM=u(a().mark((function e(t,i,s){var r,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=i&&null!==(r=i.gltf)&&void 0!==r&&r.decompressMeshes){e.next=2;break}return e.abrupt("return");case 2:n=new XP(t),o=[],l=c(oM(n));try{for(l.s();!(u=l.n()).done;)A=u.value,n.getObjectExtension(A,"KHR_draco_mesh_compression")&&o.push(iM(n,A,i,s))}catch(e){l.e(e)}finally{l.f()}return e.next=8,Promise.all(o);case 8:n.removeExtension("KHR_draco_mesh_compression");case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function iM(e,t,i,s){return sM.apply(this,arguments)}function sM(){return sM=u(a().mark((function e(t,i,s,r){var o,l,u,A,c,d,p,f,v,g,m,_,y,b;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.getObjectExtension(i,"KHR_draco_mesh_compression")){e.next=3;break}return e.abrupt("return");case 3:return l=t.getTypedArrayForBufferView(o.bufferView),u=Yb(l.buffer,l.byteOffset),A=r.parse,delete(c=n({},s))["3d-tiles"],e.next=10,A(u,ZC,c,r);case 10:for(d=e.sent,p=$C(d.attributes),f=0,v=Object.entries(p);f2&&void 0!==arguments[2]?arguments[2]:4,r=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;if(!r.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");var a=r.DracoWriter.encodeSync({attributes:e}),l=null==n||null===(i=n.parseSync)||void 0===i?void 0:i.call(n,{attributes:e}),u=r._addFauxAttributes(l.attributes),A=r.addBufferView(a),c={primitives:[{attributes:u,mode:s,extensions:o({},"KHR_draco_mesh_compression",{bufferView:A,attributes:u})}]};return c}function nM(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}function oM(e){var t,i,r,n,o,l;return a().wrap((function(s){for(;;)switch(s.prev=s.next){case 0:t=c(e.json.meshes||[]),s.prev=1,t.s();case 3:if((i=t.n()).done){s.next=24;break}r=i.value,n=c(r.primitives),s.prev=6,n.s();case 8:if((o=n.n()).done){s.next=14;break}return l=o.value,s.next=12,l;case 12:s.next=8;break;case 14:s.next=19;break;case 16:s.prev=16,s.t0=s.catch(6),n.e(s.t0);case 19:return s.prev=19,n.f(),s.finish(19);case 22:s.next=3;break;case 24:s.next=29;break;case 26:s.prev=26,s.t1=s.catch(1),t.e(s.t1);case 29:return s.prev=29,t.f(),s.finish(29);case 32:case"end":return s.stop()}}),s,null,[[1,26,29,32],[6,16,19,22]])}function aM(){return(aM=u(a().mark((function e(t){var i,s,r,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new XP(t),s=i.json,(r=i.getExtension("KHR_lights_punctual"))&&(i.json.lights=r.lights,i.removeExtension("KHR_lights_punctual")),n=c(s.nodes||[]);try{for(n.s();!(o=n.n()).done;)l=o.value,(u=i.getObjectExtension(l,"KHR_lights_punctual"))&&(l.light=u.light),i.removeObjectExtension(l,"KHR_lights_punctual")}catch(e){n.e(e)}finally{n.f()}case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function lM(){return(lM=u(a().mark((function e(t){var i,s,r,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new XP(t),(s=i.json).lights&&(TP(!(r=i.addExtension("KHR_lights_punctual")).lights),r.lights=s.lights,delete s.lights),i.json.lights){n=c(i.json.lights);try{for(n.s();!(o=n.n()).done;)l=o.value,u=l.node,i.addObjectExtension(u,"KHR_lights_punctual",l)}catch(e){n.e(e)}finally{n.f()}delete i.json.lights}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function uM(){return(uM=u(a().mark((function e(t){var i,s,r,n,o;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new XP(t),s=i.json,i.removeExtension("KHR_materials_unlit"),r=c(s.materials||[]);try{for(r.s();!(n=r.n()).done;)o=n.value,o.extensions&&o.extensions.KHR_materials_unlit&&(o.unlit=!0),i.removeObjectExtension(o,"KHR_materials_unlit")}catch(e){r.e(e)}finally{r.f()}case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function AM(){return(AM=u(a().mark((function e(t){var i,s,r,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new XP(t),s=i.json,r=i.getExtension("KHR_techniques_webgl")){n=hM(r,i),o=c(s.materials||[]);try{for(o.s();!(l=o.n()).done;)u=l.value,(A=i.getObjectExtension(u,"KHR_techniques_webgl"))&&(u.technique=Object.assign({},A,n[A.technique]),u.technique.values=dM(u.technique,i)),i.removeObjectExtension(u,"KHR_techniques_webgl")}catch(e){o.e(e)}finally{o.f()}i.removeExtension("KHR_techniques_webgl")}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function cM(){return(cM=u(a().mark((function e(t,i){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function hM(e,t){var i=e.programs,s=void 0===i?[]:i,r=e.shaders,n=void 0===r?[]:r,o=e.techniques,a=void 0===o?[]:o,l=new TextDecoder;return n.forEach((function(e){if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=l.decode(t.getTypedArrayForBufferView(e.bufferView))})),s.forEach((function(e){e.fragmentShader=n[e.fragmentShader],e.vertexShader=n[e.vertexShader]})),a.forEach((function(e){e.program=s[e.program]})),a}function dM(e,t){var i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((function(t){e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((function(e){"object"===B(i[e])&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}var pM=[hC,dC,pC,Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){var s,r=new XP(e),n=c(oM(r));try{for(n.s();!(s=n.n()).done;){var o=s.value;r.getObjectExtension(o,"KHR_draco_mesh_compression")}}catch(e){n.e(e)}finally{n.f()}},decode:function(e,t,i){return tM.apply(this,arguments)},encode:function(e){var t,i=new XP(e),s=c(i.json.meshes||[]);try{for(s.s();!(t=s.n()).done;){var r=t.value;rM(r),i.addRequiredExtension("KHR_draco_mesh_compression")}}catch(e){s.e(e)}finally{s.f()}}}),Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:function(e){return aM.apply(this,arguments)},encode:function(e){return lM.apply(this,arguments)}}),Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:function(e){return uM.apply(this,arguments)},encode:function(e){var t=new XP(e),i=t.json;if(t.materials){var s,r=c(i.materials||[]);try{for(r.s();!(s=r.n()).done;){var n=s.value;n.unlit&&(delete n.unlit,t.addObjectExtension(n,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}catch(e){r.e(e)}finally{r.f()}}}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:function(e){return AM.apply(this,arguments)},encode:function(e,t){return cM.apply(this,arguments)}})];function fM(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0,r=pM.filter((function(e){return mM(e.name,i)})),n=c(r);try{for(n.s();!(t=n.n()).done;){var o,a=t.value;null===(o=a.preprocess)||void 0===o||o.call(a,e,i,s)}}catch(e){n.e(e)}finally{n.f()}}function vM(e){return gM.apply(this,arguments)}function gM(){return gM=u(a().mark((function e(t){var i,s,r,n,o,l,u,A=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=A.length>1&&void 0!==A[1]?A[1]:{},s=A.length>2?A[2]:void 0,r=pM.filter((function(e){return mM(e.name,i)})),n=c(r),e.prev=4,n.s();case 6:if((o=n.n()).done){e.next=12;break}return l=o.value,e.next=10,null===(u=l.decode)||void 0===u?void 0:u.call(l,t,i,s);case 10:e.next=6;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(4),n.e(e.t0);case 17:return e.prev=17,n.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,null,[[4,14,17,20]])}))),gM.apply(this,arguments)}function mM(e,t){var i,s=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in s&&!s[e])}var _M={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},yM={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"},bM=function(){function e(){x(this,e),vb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),vb(this,"json",void 0)}return C(e,[{key:"normalize",value:function(e,t){this.json=e.json;var i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){var t,i=new XP(e),s=i.json,r=c(s.images||[]);try{for(r.s();!(t=r.n()).done;){var n=t.value,o=i.getObjectExtension(n,"KHR_binary_glTF");o&&Object.assign(n,o),i.removeObjectExtension(n,"KHR_binary_glTF")}}catch(e){r.e(e)}finally{r.f()}s.buffers&&s.buffers[0]&&delete s.buffers[0].uri,i.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}},{key:"_addAsset",value:function(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}},{key:"_convertTopLevelObjectsToArrays",value:function(e){for(var t in _M)this._convertTopLevelObjectToArray(e,t)}},{key:"_convertTopLevelObjectToArray",value:function(e,t){var i=e[t];if(i&&!Array.isArray(i))for(var s in e[t]=[],i){var r=i[s];r.id=r.id||s;var n=e[t].length;e[t].push(r),this.idToIndexMap[t][s]=n}}},{key:"_convertObjectIdsToArrayIndices",value:function(e){for(var t in _M)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));var i,s=c(e.textures);try{for(s.s();!(i=s.n()).done;){var r=i.value;this._convertTextureIds(r)}}catch(e){s.e(e)}finally{s.f()}var n,o=c(e.meshes);try{for(o.s();!(n=o.n()).done;){var a=n.value;this._convertMeshIds(a)}}catch(e){o.e(e)}finally{o.f()}var l,u=c(e.nodes);try{for(u.s();!(l=u.n()).done;){var A=l.value;this._convertNodeIds(A)}}catch(e){u.e(e)}finally{u.f()}var h,d=c(e.scenes);try{for(d.s();!(h=d.n()).done;){var p=h.value;this._convertSceneIds(p)}}catch(e){d.e(e)}finally{d.f()}}},{key:"_convertTextureIds",value:function(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}},{key:"_convertMeshIds",value:function(e){var t,i=c(e.primitives);try{for(i.s();!(t=i.n()).done;){var s=t.value,r=s.attributes,n=s.indices,o=s.material;for(var a in r)r[a]=this._convertIdToIndex(r[a],"accessor");n&&(s.indices=this._convertIdToIndex(n,"accessor")),o&&(s.material=this._convertIdToIndex(o,"material"))}}catch(e){i.e(e)}finally{i.f()}}},{key:"_convertNodeIds",value:function(e){var t=this;e.children&&(e.children=e.children.map((function(e){return t._convertIdToIndex(e,"node")}))),e.meshes&&(e.meshes=e.meshes.map((function(e){return t._convertIdToIndex(e,"mesh")})))}},{key:"_convertSceneIds",value:function(e){var t=this;e.nodes&&(e.nodes=e.nodes.map((function(e){return t._convertIdToIndex(e,"node")})))}},{key:"_convertIdsToIndices",value:function(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);var i,s=c(e[t]);try{for(s.s();!(i=s.n()).done;){var r=i.value;for(var n in r){var o=r[n],a=this._convertIdToIndex(o,n);r[n]=a}}}catch(e){s.e(e)}finally{s.f()}}},{key:"_convertIdToIndex",value:function(e,t){var i=yM[t];if(i in this.idToIndexMap){var s=this.idToIndexMap[i][e];if(!Number.isFinite(s))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return s}return e}},{key:"_updateObjects",value:function(e){var t,i=c(this.json.buffers);try{for(i.s();!(t=i.n()).done;){delete t.value.type}}catch(e){i.e(e)}finally{i.f()}}},{key:"_updateMaterial",value:function(e){var t,i=c(e.materials);try{var s=function(){var i=t.value;i.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var s=(null===(r=i.values)||void 0===r?void 0:r.tex)||(null===(n=i.values)||void 0===n?void 0:n.texture2d_0),o=e.textures.findIndex((function(e){return e.id===s}));-1!==o&&(i.pbrMetallicRoughness.baseColorTexture={index:o})};for(i.s();!(t=i.n()).done;){var r,n;s()}}catch(e){i.e(e)}finally{i.f()}}}]),e}();function wM(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(new bM).normalize(e,t)}var BM={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},xM={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},PM=10240,CM=10241,MM=10242,EM=10243,FM=10497,kM=9986,IM={magFilter:PM,minFilter:CM,wrapS:MM,wrapT:EM},DM=(o(e={},PM,9729),o(e,CM,kM),o(e,MM,FM),o(e,EM,FM),e);var SM=function(){function e(){x(this,e),vb(this,"baseUri",""),vb(this,"json",{}),vb(this,"buffers",[]),vb(this,"images",[])}return C(e,[{key:"postProcess",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e.json,s=e.buffers,r=void 0===s?[]:s,n=e.images,o=void 0===n?[]:n,a=e.baseUri,l=void 0===a?"":a;return TP(i),this.baseUri=l,this.json=i,this.buffers=r,this.images=o,this._resolveTree(this.json,t),this.json}},{key:"_resolveTree",value:function(e){var t=this;e.bufferViews&&(e.bufferViews=e.bufferViews.map((function(e,i){return t._resolveBufferView(e,i)}))),e.images&&(e.images=e.images.map((function(e,i){return t._resolveImage(e,i)}))),e.samplers&&(e.samplers=e.samplers.map((function(e,i){return t._resolveSampler(e,i)}))),e.textures&&(e.textures=e.textures.map((function(e,i){return t._resolveTexture(e,i)}))),e.accessors&&(e.accessors=e.accessors.map((function(e,i){return t._resolveAccessor(e,i)}))),e.materials&&(e.materials=e.materials.map((function(e,i){return t._resolveMaterial(e,i)}))),e.meshes&&(e.meshes=e.meshes.map((function(e,i){return t._resolveMesh(e,i)}))),e.nodes&&(e.nodes=e.nodes.map((function(e,i){return t._resolveNode(e,i)}))),e.skins&&(e.skins=e.skins.map((function(e,i){return t._resolveSkin(e,i)}))),e.scenes&&(e.scenes=e.scenes.map((function(e,i){return t._resolveScene(e,i)}))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}},{key:"getScene",value:function(e){return this._get("scenes",e)}},{key:"getNode",value:function(e){return this._get("nodes",e)}},{key:"getSkin",value:function(e){return this._get("skins",e)}},{key:"getMesh",value:function(e){return this._get("meshes",e)}},{key:"getMaterial",value:function(e){return this._get("materials",e)}},{key:"getAccessor",value:function(e){return this._get("accessors",e)}},{key:"getCamera",value:function(e){return null}},{key:"getTexture",value:function(e){return this._get("textures",e)}},{key:"getSampler",value:function(e){return this._get("samplers",e)}},{key:"getImage",value:function(e){return this._get("images",e)}},{key:"getBufferView",value:function(e){return this._get("bufferViews",e)}},{key:"getBuffer",value:function(e){return this._get("buffers",e)}},{key:"_get",value:function(e,t){if("object"===B(t))return t;var i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}},{key:"_resolveScene",value:function(e,t){var i=this;return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((function(e){return i.getNode(e)})),e}},{key:"_resolveNode",value:function(e,t){var i=this;return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((function(e){return i.getNode(e)}))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce((function(e,t){var s=i.getMesh(t);return e.id=s.id,e.primitives=e.primitives.concat(s.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}},{key:"_resolveSkin",value:function(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}},{key:"_resolveMesh",value:function(e,t){var i=this;return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((function(e){var t=(e=n({},e)).attributes;for(var s in e.attributes={},t)e.attributes[s]=i.getAccessor(t[s]);return void 0!==e.indices&&(e.indices=i.getAccessor(e.indices)),void 0!==e.material&&(e.material=i.getMaterial(e.material)),e}))),e}},{key:"_resolveMaterial",value:function(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture=n({},e.normalTexture),e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture=n({},e.occlustionTexture),e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture=n({},e.emmisiveTexture),e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness=n({},e.pbrMetallicRoughness);var i=e.pbrMetallicRoughness;i.baseColorTexture&&(i.baseColorTexture=n({},i.baseColorTexture),i.baseColorTexture.texture=this.getTexture(i.baseColorTexture.index)),i.metallicRoughnessTexture&&(i.metallicRoughnessTexture=n({},i.metallicRoughnessTexture),i.metallicRoughnessTexture.texture=this.getTexture(i.metallicRoughnessTexture.index))}return e}},{key:"_resolveAccessor",value:function(e,t){var i,s;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,xM[i]),e.components=(s=e.type,BM[s]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){var r=e.bufferView.buffer,n=zP(e,e.bufferView),o=n.ArrayType,a=n.byteLength,l=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+r.byteOffset,u=r.arrayBuffer.slice(l,l+a);e.bufferView.byteStride&&(u=this._getValueFromInterleavedBuffer(r,l,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new o(u)}return e}},{key:"_getValueFromInterleavedBuffer",value:function(e,t,i,s,r){for(var n=new Uint8Array(r*s),o=0;o1&&void 0!==arguments[1]?arguments[1]:0;return"".concat(String.fromCharCode(e.getUint8(t+0))).concat(String.fromCharCode(e.getUint8(t+1))).concat(String.fromCharCode(e.getUint8(t+2))).concat(String.fromCharCode(e.getUint8(t+3)))}function UM(e,t,i){ob(e.header.byteLength>20);var s=t.getUint32(i+0,LM),r=t.getUint32(i+4,LM);return i+=8,ob(0===r),NM(e,t,i,s),i+=s,i+=QM(e,t,i,e.header.byteLength)}function OM(e,t,i,s){return ob(e.header.byteLength>20),function(e,t,i,s){for(;i+8<=e.header.byteLength;){var r=t.getUint32(i+0,LM),n=t.getUint32(i+4,LM);switch(i+=8,n){case 1313821514:NM(e,t,i,r);break;case 5130562:QM(e,t,i,r);break;case 0:s.strict||NM(e,t,i,r);break;case 1:s.strict||QM(e,t,i,r)}i+=Jb(r,4)}}(e,t,i,s),i+e.header.byteLength}function NM(e,t,i,s){var r=new Uint8Array(t.buffer,i,s),n=new TextDecoder("utf8").decode(r);return e.json=JSON.parse(n),Jb(s,4)}function QM(e,t,i,s){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:s,arrayBuffer:t.buffer}),Jb(s,4)}function VM(e,t){return HM.apply(this,arguments)}function HM(){return HM=u(a().mark((function e(t,i){var s,r,n,o,l,u,A,c,h,d,p=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(s=p.length>2&&void 0!==p[2]?p[2]:0,r=p.length>3?p[3]:void 0,n=p.length>4?p[4]:void 0,jM(t,i,s,r),wM(t,{normalize:null==r||null===(o=r.gltf)||void 0===o?void 0:o.normalize}),fM(t,r,n),c=[],null==r||null===(l=r.gltf)||void 0===l||!l.loadBuffers||!t.json.buffers){e.next=10;break}return e.next=10,GM(t,r,n);case 10:return null!=r&&null!==(u=r.gltf)&&void 0!==u&&u.loadImages&&(h=WM(t,r,n),c.push(h)),d=vM(t,r,n),c.push(d),e.next=15,Promise.all(c);case 15:return e.abrupt("return",null!=r&&null!==(A=r.gltf)&&void 0!==A&&A.postProcess?TM(t,r):t);case 16:case"end":return e.stop()}}),e)}))),HM.apply(this,arguments)}function jM(e,t,i,s){(s.uri&&(e.baseUri=s.uri),t instanceof ArrayBuffer&&!function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=new DataView(e),r=i.magic,n=void 0===r?1735152710:r,o=s.getUint32(t,!1);return o===n||1735152710===o}(t,i,s))&&(t=(new TextDecoder).decode(t));if("string"==typeof t)e.json=zb(t);else if(t instanceof ArrayBuffer){var r={};i=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=new DataView(t),r=RM(s,i+0),n=s.getUint32(i+4,LM),o=s.getUint32(i+8,LM);switch(Object.assign(e,{header:{byteOffset:i,byteLength:o,hasBinChunk:!1},type:r,version:n,json:{},binChunks:[]}),i+=12,e.version){case 1:return UM(e,s,i);case 2:return OM(e,s,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}(r,t,i,s.glb),TP("glTF"===r.type,"Invalid GLB magic string ".concat(r.type)),e._glb=r,e.json=r.json}else TP(!1,"GLTF: must be ArrayBuffer or string");var n=e.json.buffers||[];if(e.buffers=new Array(n.length).fill(null),e._glb&&e._glb.header.hasBinChunk){var o=e._glb.binChunks;e.buffers[0]={arrayBuffer:o[0].arrayBuffer,byteOffset:o[0].byteOffset,byteLength:o[0].byteLength}}var a=e.json.images||[];e.images=new Array(a.length).fill({})}function GM(e,t,i){return zM.apply(this,arguments)}function zM(){return(zM=u(a().mark((function e(t,i,s){var r,n,o,l,u,A,c,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:r=t.json.buffers||[],n=0;case 2:if(!(n1&&void 0!==u[1]?u[1]:{},s=u.length>2?u[2]:void 0,(i=n(n({},ZM.options),i)).gltf=n(n({},ZM.options.gltf),i.gltf),r=i.byteOffset,o=void 0===r?0:r,l={},e.next=8,VM(l,t,o,i,s);case 8:return e.abrupt("return",e.sent);case 9:case"end":return e.stop()}}),e)}))),qM.apply(this,arguments)}var $M=function(){function e(t){x(this,e)}return C(e,[{key:"load",value:function(e,t,i,s,r,n,o){!function(e,t,i,s,r,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(function(o){s.basePath=tE(t),iE(e,t,o,i,s,r,n),a.processes--}),(function(e){a.processes--,o(e)})):e.dataSource.getGLTF(t,(function(o){s.basePath=tE(t),iE(e,t,o,i,s,r,n),a.processes--}),(function(e){a.processes--,o(e)}))}(e,t,i,s=s||{},r,(function(){_e.scheduleTask((function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1)})),n&&n()}),(function(t){e.error(t),o&&o(t),r.fire("error",t)}))}},{key:"parse",value:function(e,t,i,s,r,n,o){iE(e,"",t,i,s=s||{},r,(function(){r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1),n&&n()}))}}]),e}();function eE(e){for(var t={},i={},s=e.metaObjects||[],r={},n=0,o=s.length;n0)for(var A=0;A0){null==y&&e.log("Warning: 'name' properties not found on glTF scene nodes - will randomly-generate object IDs in XKT");var b=y;if(e.metaModelCorrections){var w=e.metaModelCorrections.eachChildRoot[b];if(w){var B=e.metaModelCorrections.eachRootStats[w.id];B.countChildren++,B.countChildren>=B.numChildren&&(n.createEntity({id:w.id,meshIds:aE,isObject:!0}),aE.length=0)}else{e.metaModelCorrections.metaObjectsMap[b]&&(n.createEntity({id:b,meshIds:aE,isObject:!0}),aE.length=0)}}else n.createEntity({id:b,meshIds:aE,isObject:!0}),aE.length=0}}}function uE(e,t){e.plugin.error(t)}var AE={DEFAULT:{}},cE=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"GLTFLoader",e,r))._sceneModelLoader=new $M(b(s),r),s.dataSource=r.dataSource,s.objectDefaults=r.objectDefaults,s}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Sh}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0,dtxEnabled:t.dtxEnabled})),s=i.id;if(!t.src&&!t.gltf)return this.error("load() param expected: src or gltf"),i;if(t.metaModelSrc||t.metaModelJSON){var r=t.objectDefaults||this._objectDefaults||AE,n=function(n){var o;if(e.viewer.metaScene.createMetaModel(s,n,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes}),e.viewer.scene.canvas.spinner.processes--,t.includeTypes){o={};for(var a=0,l=t.includeTypes.length;a2&&void 0!==arguments[2]?arguments[2]:{},s="lightgrey",r=i.hoverColor||"rgba(0,0,0,0.4)",n=i.textColor||"black",o=500,a=o+o/3,l=a/24,u=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],A=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;for(var c=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-.7071,.7071],up:[0,.7071,.7071]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}],h=0,d=A.length;h=c[0]*l&&t<=(c[0]+c[2])*l&&i>=c[1]*l&&i<=(c[1]+c[3])*l)return s}return-1},this.setAreaHighlighted=function(e,t){var i=v[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,y()},this.getAreaDir=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)}}var dE=$.vec3(),pE=$.vec3();$.mat4();var fE=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),s=t.call(this,"NavCube",e,r),e.navCube=b(s);var n=!0;try{s._navCubeScene=new $i(e,{canvasId:r.canvasId,canvasElement:r.canvasElement,transparent:!0}),s._navCubeCanvas=s._navCubeScene.canvas.canvas,s._navCubeScene.input.keyboardEnabled=!1}catch(e){return s.error(e),y(s)}var o=s._navCubeScene;o.clearLights(),new bi(o,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(o,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(o,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),s._navCubeCamera=o.camera,s._navCubeCamera.ortho.scale=7,s._navCubeCamera.ortho.near=.1,s._navCubeCamera.ortho.far=2e3,o.edgeMaterial.edgeColor=[.2,.2,.2],o.edgeMaterial.edgeAlpha=.6,s._zUp=Boolean(e.camera.zUp);var a=b(s);s.setIsProjectNorth(r.isProjectNorth),s.setProjectNorthOffsetAngle(r.projectNorthOffsetAngle);var l,u=(l=$.mat4(),function(e,t,i){return $.identityMat4(l),$.rotationMat4v(e*a._projectNorthOffsetAngle*$.DEGTORAD,[0,1,0],l),$.transformVec3(l,t,i)});s._synchCamera=function(){var t=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),i=$.vec3(),s=$.vec3(),r=$.vec3();return function(){var n=e.camera.eye,o=e.camera.look,l=e.camera.up;i=$.mulVec3Scalar($.normalizeVec3($.subVec3(n,o,i)),5),a._isProjectNorth&&a._projectNorthOffsetAngle&&(i=u(-1,i,dE),l=u(-1,l,pE)),a._zUp?($.transformVec3(t,i,s),$.transformVec3(t,l,r),a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=$.transformVec3(t,i,s),a._navCubeCamera.up=$.transformPoint3(t,l,r)):(a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=i,a._navCubeCamera.up=l)}}(),s._cubeTextureCanvas=new hE(e,o,r),s._cubeSampler=new On(o,{image:s._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),s._cubeMesh=new nn(o,{geometry:new Ti(o,{primitive:"triangles",normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),material:new Ni(o,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:s._cubeSampler,emissiveMap:s._cubeSampler}),visible:!!n,edges:!0}),s._shadow=!1===r.shadowVisible?null:new nn(o,{geometry:new Ti(o,an({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new Ni(o,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!!n,pickable:!1,backfaces:!1}),s._onCameraMatrix=e.camera.on("matrix",s._synchCamera),s._onCameraWorldAxis=e.camera.on("worldAxis",(function(){e.camera.zUp?(s._zUp=!0,s._cubeTextureCanvas.setZUp(),s._repaint(),s._synchCamera()):e.camera.yUp&&(s._zUp=!1,s._cubeTextureCanvas.setYUp(),s._repaint(),s._synchCamera())})),s._onCameraFOV=e.camera.perspective.on("fov",(function(e){s._synchProjection&&(s._navCubeCamera.perspective.fov=e)})),s._onCameraProjection=e.camera.on("projection",(function(e){s._synchProjection&&(s._navCubeCamera.projection="ortho"===e||"perspective"===e?e:"perspective")}));var A=-1;function c(t,i){var s=(t-d)*-_,r=(i-p)*-_;e.camera.orbitYaw(s),e.camera.orbitPitch(-r),d=t,p=i}function h(e){var t=[0,0];if(e){for(var i=e.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var d,p,f=null,v=null,g=!1,m=!1,_=.5;a._navCubeCanvas.addEventListener("mouseenter",a._onMouseEnter=function(e){m=!0}),a._navCubeCanvas.addEventListener("mouseleave",a._onMouseLeave=function(e){m=!1}),a._navCubeCanvas.addEventListener("mousedown",a._onMouseDown=function(e){if(1===e.which){f=e.x,v=e.y,d=e.clientX,p=e.clientY;var t=h(e),i=o.pick({canvasPos:t});g=!!i}}),document.addEventListener("mouseup",a._onMouseUp=function(e){if(1===e.which&&(g=!1,null!==f)){var t=h(e),i=o.pick({canvasPos:t,pickSurface:!0});if(i&&i.uv){var s=a._cubeTextureCanvas.getArea(i.uv);if(s>=0&&(document.body.style.cursor="pointer",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),s>=0)){if(a._cubeTextureCanvas.setAreaHighlighted(s,!0),A=s,a._repaint(),e.xf+3||e.yv+3)return;var r=a._cubeTextureCanvas.getAreaDir(s);if(r){var n=a._cubeTextureCanvas.getAreaUp(s);a._isProjectNorth&&a._projectNorthOffsetAngle&&(r=u(1,r,dE),n=u(1,n,pE)),w(r,n,(function(){A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),document.body.style.cursor="pointer",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),s>=0&&(a._cubeTextureCanvas.setAreaHighlighted(s,!1),A=-1,a._repaint())}))}}}}}),document.addEventListener("mousemove",a._onMouseMove=function(e){if(A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),1!==e.buttons||g){if(g){var t=e.clientX,i=e.clientY;return document.body.style.cursor="move",void c(t,i)}if(m){var s=h(e),r=o.pick({canvasPos:s,pickSurface:!0});if(r){if(r.uv){document.body.style.cursor="pointer";var n=a._cubeTextureCanvas.getArea(r.uv);if(n===A)return;A>=0&&a._cubeTextureCanvas.setAreaHighlighted(A,!1),n>=0&&(a._cubeTextureCanvas.setAreaHighlighted(n,!0),a._repaint(),A=n)}}else document.body.style.cursor="default",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1)}}});var w=function(){var t=$.vec3();return function(i,s,r){var n=a._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=$.getAABB3Diag(n);$.getAABB3Center(n,t);var l=Math.abs(o/Math.tan(a._cameraFitFOV*$.DEGTORAD));e.cameraControl.pivotPos=t,a._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:s||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV,duration:a._cameraFlyDuration},r):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:s||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV},r)}}();return s._onUpdated=e.localeService.on("updated",(function(){s._cubeTextureCanvas.clear(),s._repaint()})),s.setVisible(r.visible),s.setCameraFitFOV(r.cameraFitFOV),s.setCameraFly(r.cameraFly),s.setCameraFlyDuration(r.cameraFlyDuration),s.setFitVisible(r.fitVisible),s.setSynchProjection(r.synchProjection),s}return C(i,[{key:"send",value:function(e,t){if("language"===e)this._cubeTextureCanvas.clear(),this._repaint()}},{key:"_repaint",value:function(){var e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow&&(this._shadow.visible=e),this._navCubeCanvas.style.visibility=e?"visible":"hidden")}},{key:"getVisible",value:function(){return!!this._navCubeCanvas&&this._cubeMesh.visible}},{key:"setFitVisible",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._fitVisible=e}},{key:"getFitVisible",value:function(){return this._fitVisible}},{key:"setCameraFly",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._cameraFly=e}},{key:"getCameraFly",value:function(){return this._cameraFly}},{key:"setCameraFitFOV",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:45;this._cameraFitFOV=e}},{key:"getCameraFitFOV",value:function(){return this._cameraFitFOV}},{key:"setCameraFlyDuration",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.5;this._cameraFlyDuration=e}},{key:"getCameraFlyDuration",value:function(){return this._cameraFlyDuration}},{key:"setSynchProjection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._synchProjection=e}},{key:"getSynchProjection",value:function(){return this._synchProjection}},{key:"setIsProjectNorth",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._isProjectNorth=e}},{key:"getIsProjectNorth",value:function(){return this._isProjectNorth}},{key:"setProjectNorthOffsetAngle",value:function(e){this._projectNorthOffsetAngle=e}},{key:"getProjectNorthOffsetAngle",value:function(){return this._projectNorthOffsetAngle}},{key:"destroy",value:function(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,f(w(i.prototype),"destroy",this).call(this)}}]),i}(),vE=$.vec3(),gE=function(){function e(){x(this,e)}return C(e,[{key:"load",value:function(e,t){var i=e.scene.canvas.spinner;i.processes++,mE(e,t,(function(t){yE(e,t,(function(){BE(e,t),i.processes--,_e.scheduleTask((function(){e.fire("loaded",!0,!1)}))}))}))}},{key:"parse",value:function(e,t,i,s){if(t){var r=_E(e,t,null);i&&wE(e,i,s),BE(e,r),e.src=null,e.fire("loaded",!0,!1)}else this.warn("load() param expected: objText")}}]),e}(),mE=function(e,t,i){xE(t,(function(s){var r=_E(e,s,t);i(r)}),(function(t){e.error(t)}))},_E=function(){var e={vertex_pattern:/^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,normal_pattern:/^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,uv_pattern:/^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,face_vertex:/^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,face_vertex_uv:/^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,face_vertex_uv_normal:/^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,face_vertex_normal:/^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,object_pattern:/^[og]\s*(.+)?/,smoothing_pattern:/^s\s+(\d+|on|off)/,material_library_pattern:/^mtllib /,material_use_pattern:/^usemtl /};return function(s,r,n){var o={src:n=n||"",basePath:t(n),objects:[],object:{},positions:[],normals:[],uv:[],materialLibraries:{}};i(o,"",!1),-1!==r.indexOf("\r\n")&&(r=r.replace("\r\n","\n"));for(var a=r.split("\n"),l="",u="",A="",d=[],p="function"==typeof"".trimLeft,f=0,v=a.length;f=0?i-1:i+t/3)}function r(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function n(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function o(e,t,i,s){var r=e.positions,n=e.object.geometry.positions;n.push(r[t+0]),n.push(r[t+1]),n.push(r[t+2]),n.push(r[i+0]),n.push(r[i+1]),n.push(r[i+2]),n.push(r[s+0]),n.push(r[s+1]),n.push(r[s+2])}function a(e,t){var i=e.positions,s=e.object.geometry.positions;s.push(i[t+0]),s.push(i[t+1]),s.push(i[t+2])}function l(e,t,i,s){var r=e.normals,n=e.object.geometry.normals;n.push(r[t+0]),n.push(r[t+1]),n.push(r[t+2]),n.push(r[i+0]),n.push(r[i+1]),n.push(r[i+2]),n.push(r[s+0]),n.push(r[s+1]),n.push(r[s+2])}function u(e,t,i,s){var r=e.uv,n=e.object.geometry.uv;n.push(r[t+0]),n.push(r[t+1]),n.push(r[i+0]),n.push(r[i+1]),n.push(r[s+0]),n.push(r[s+1])}function A(e,t){var i=e.uv,s=e.object.geometry.uv;s.push(i[t+0]),s.push(i[t+1])}function c(e,t,i,a,A,c,h,d,p,f,v,g,m){var _,y=e.positions.length,b=s(t,y),w=s(i,y),B=s(a,y);if(void 0===A?o(e,b,w,B):(o(e,b,w,_=s(A,y)),o(e,w,B,_)),void 0!==c){var x=e.uv.length;b=n(c,x),w=n(h,x),B=n(d,x),void 0===A?u(e,b,w,B):(u(e,b,w,_=n(p,x)),u(e,w,B,_))}if(void 0!==f){var P=e.normals.length;b=r(f,P),w=f===v?b:r(v,P),B=f===g?b:r(g,P),void 0===A?l(e,b,w,B):(l(e,b,w,_=r(m,P)),l(e,w,B,_))}}function h(e,t,i){e.object.geometry.type="Line";for(var r=e.positions.length,o=e.uv.length,l=0,u=t.length;l=0?o.substring(0,a):o).toLowerCase(),u=(u=a>=0?o.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,h),h={id:u},d=!0;break;case"ka":h.ambient=s(u);break;case"kd":h.diffuse=s(u);break;case"ks":h.specular=s(u);break;case"map_kd":h.diffuseMap||(h.diffuseMap=t(e,n,u,"sRGB"));break;case"map_ks":h.specularMap||(h.specularMap=t(e,n,u,"linear"));break;case"map_bump":case"bump":h.normalMap||(h.normalMap=t(e,n,u));break;case"ns":h.shininess=parseFloat(u);break;case"d":(A=parseFloat(u))<1&&(h.alpha=A,h.alphaMode="blend");break;case"tr":(A=parseFloat(u))>0&&(h.alpha=1-A,h.alphaMode="blend")}d&&i(e,h)};function t(e,t,i,s){var r={},n=i.split(/\s+/),o=n.indexOf("-bm");return o>=0&&n.splice(o,2),(o=n.indexOf("-s"))>=0&&(r.scale=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),(o=n.indexOf("-o"))>=0&&(r.translate=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),r.src=t+n.join(" ").trim(),r.flipY=!0,r.encoding=s||"linear",new On(e,r).id}function i(e,t){new Ni(e,t)}function s(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function BE(e,t){for(var i=0,s=t.objects.length;i0&&(o.normals=n.normals),n.uv.length>0&&(o.uv=n.uv);for(var a=new Array(o.positions.length/3),l=0;l0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new wn(this.viewer.scene,le.apply(t,{isModel:!0})),s=i.id,r=t.src;if(!r)return this.error("load() param expected: src"),i;if(t.metaModelSrc){var n=t.metaModelSrc;le.loadJSON(n,(function(n){e.viewer.metaScene.createMetaModel(s,n),e._sceneGraphLoader.load(i,r,t)}),(function(t){e.error("load(): Failed to load model modelMetadata for model '".concat(s," from '").concat(n,"' - ").concat(t))}))}else this._sceneGraphLoader.load(i,r,t);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(s)})),i}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),CE=new Float64Array([0,0,1]),ME=new Float64Array(4),EE=function(){function e(t){x(this,e),this.id=null,this._viewer=t.viewer,this._visible=!1,this._pos=$.vec3(),this._origin=$.vec3(),this._rtcPos=$.vec3(),this._baseDir=$.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),Re(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=$.vec3PairToQuaternion(CE,e,ME)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new wn(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});var s,r,n=this._rootNode,o={arrowHead:new Ti(n,an({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ti(n,an({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Ti(n,an({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Ti(n,Jn({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Ti(n,Jn({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Ti(n,Jn({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Ti(n,an({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Ti(n,an({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},a={pickable:new Ni(n,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new Ni(n,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Vi(n,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new Ni(n,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new Vi(n,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new Ni(n,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new Vi(n,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new Ni(n,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new Vi(n,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new Vi(n,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:n.addChild(new nn(n,{geometry:new Ti(n,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new Ni(n,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new Vi(n,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1],isObject:!1}),e),planeFrame:n.addChild(new nn(n,{geometry:new Ti(n,Jn({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(n,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new Vi(n,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45],isObject:!1}),e),xCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.red,matrix:(s=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),r=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4()),$.mulMat4(r,s,$.identityMat4())),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,matrix:function(){var e=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),t=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,-.07,-.8,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(0*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,-.8,-.07,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(.07,0,-.8,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(.8,0,-.07,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.blue,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(.8,-.07,0,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4());return $.mulMat4(e,t,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(.05,-.8,0,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:n.addChild(new nn(n,{geometry:new Ti(n,ln({radius:.05})),material:a.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:n.addChild(new nn(n,{geometry:o.axis,material:a.red,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:n.addChild(new nn(n,{geometry:o.axis,material:a.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:n.addChild(new nn(n,{geometry:o.axis,material:a.blue,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:n.addChild(new nn(n,{geometry:new Ti(n,Jn({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(n,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Vi(n,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45],isObject:!1}),e),xHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.red,highlighted:!0,highlightMaterial:a.highlightRed,matrix:function(){var e=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),t=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.green,highlighted:!0,highlightMaterial:a.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.blue,highlighted:!0,highlightMaterial:a.highlightBlue,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.red,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.green,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this,i=!1,s=-1,r=0,n=1,o=2,a=3,l=4,u=5,A=this._rootNode,c=null,h=null,d=$.vec2(),p=$.vec3([1,0,0]),f=$.vec3([0,1,0]),v=$.vec3([0,0,1]),g=this._viewer.scene.canvas.canvas,m=this._viewer.camera,_=this._viewer.scene,y=$.vec3([0,0,0]),b=-1;this._onCameraViewMatrix=_.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=_.camera.on("projMatrix",(function(){})),this._onSceneTick=_.on("tick",(function(){var t=Math.abs($.lenVec3($.subVec3(_.camera.eye,e._pos,y)));if(t!==b&&"perspective"===m.projection){var i=.07*(Math.tan(m.perspective.fov*$.DEGTORAD)*t);A.scale=[i,i,i],b=t}if("ortho"===m.projection){var s=m.ortho.scale/10;A.scale=[s,s,s],b=t}}));var w,B,x,P,C,M=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),E=function(){var e=$.mat4();return function(i,s){return $.quaternionToMat4(t._rootNode.quaternion,e),$.transformVec3(e,i,s),$.normalizeVec3(s),s}}(),F=(w=$.vec3(),function(e){var t=Math.abs(e[0]);return t>Math.abs(e[1])&&t>Math.abs(e[2])?$.cross3Vec3(e,[0,1,0],w):$.cross3Vec3(e,[1,0,0],w),$.cross3Vec3(w,e,w),$.normalizeVec3(w),w}),k=(B=$.vec3(),x=$.vec3(),P=$.vec4(),function(e,i,s){E(e,P);var r=F(P,i,s);D(i,r,B),D(s,r,x),$.subVec3(x,B);var n=$.dotVec3(x,P);t._pos[0]+=P[0]*n,t._pos[1]+=P[1]*n,t._pos[2]+=P[2]*n,t._rootNode.position=t._pos,t._sectionPlane&&(t._sectionPlane.pos=t._pos)}),I=function(){var e=$.vec4(),i=$.vec4(),s=$.vec4(),r=$.vec4();return function(n,o,a){if(E(n,r),!(D(o,r,e)&&D(a,r,i))){var l=F(r,o,a);D(o,l,e,1),D(a,l,i,1);var u=$.dotVec3(e,r);e[0]-=u*r[0],e[1]-=u*r[1],e[2]-=u*r[2],u=$.dotVec3(i,r),i[0]-=u*r[0],i[1]-=u*r[1],i[2]-=u*r[2]}$.normalizeVec3(e),$.normalizeVec3(i),u=$.dotVec3(e,i),u=$.clamp(u,-1,1);var A=Math.acos(u)*$.RADTODEG;$.cross3Vec3(e,i,s),$.dotVec3(s,r)<0&&(A=-A),t._rootNode.rotate(n,A),S()}}(),D=function(){var e=$.vec4([0,0,0,1]),i=$.mat4();return function(s,r,n,o){o=o||0,e[0]=s[0]/g.width*2-1,e[1]=-(s[1]/g.height*2-1),e[2]=0,e[3]=1,$.mulMat4(m.projMatrix,m.viewMatrix,i),$.inverseMat4(i),$.transformVec4(i,e,e),$.mulVec4Scalar(e,1/e[3]);var a=m.eye;$.subVec4(e,a,e);var l=t._sectionPlane.pos,u=-$.dotVec3(l,r)-o,A=$.dotVec3(r,e);if(Math.abs(A)>.005){var c=-($.dotVec3(r,a)+u)/A;return $.mulVec3Scalar(e,c,n),$.addVec3(n,a),$.subVec3(n,l,n),!0}return!1}}(),S=function(){var e=$.vec3(),i=$.mat4();return function(){t.sectionPlane&&($.quaternionToMat4(A.quaternion,i),$.transformVec3(i,[0,0,1],e),t._setSectionPlaneDir(e))}}(),T=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(function(t){if(e._visible&&!T){var A;switch(i=!1,C&&(C.visible=!1),t.entity.id){case e._displayMeshes.xAxisArrowHandle.id:case e._displayMeshes.xAxisHandle.id:A=e._affordanceMeshes.xAxisArrow,c=r;break;case e._displayMeshes.yAxisArrowHandle.id:case e._displayMeshes.yShaftHandle.id:A=e._affordanceMeshes.yAxisArrow,c=n;break;case e._displayMeshes.zAxisArrowHandle.id:case e._displayMeshes.zAxisHandle.id:A=e._affordanceMeshes.zAxisArrow,c=o;break;case e._displayMeshes.xCurveHandle.id:A=e._affordanceMeshes.xHoop,c=a;break;case e._displayMeshes.yCurveHandle.id:A=e._affordanceMeshes.yHoop,c=l;break;case e._displayMeshes.zCurveHandle.id:A=e._affordanceMeshes.zHoop,c=u;break;default:return void(c=s)}A&&(A.visible=!0),C=A,i=!0}})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(function(t){e._visible&&(C&&(C.visible=!1),C=null,c=s)})),g.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&i&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){T=!0;var s=M(t);h=c,d[0]=s[0],d[1]=s[1]}}),g.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&T){var i=M(t),s=i[0],A=i[1];switch(h){case r:k(p,d,i);break;case n:k(f,d,i);break;case o:k(v,d,i);break;case a:I(p,d,i);break;case l:I(f,d,i);break;case u:I(v,d,i)}d[0]=s,d[1]=A}}),g.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,T&&(t.which,T=!1,i=!1))}),g.addEventListener("wheel",this._canvasWheelListener=function(t){if(e._visible)Math.max(-1,Math.min(1,40*-t.deltaY))})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix),r.off(this._onCameraControlHover),r.off(this._onCameraControlHoverLeave)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),FE=function(){function e(t,i,s){var r=this;x(this,e),this.id=s.id,this._sectionPlane=s,this._mesh=new nn(i,{id:s.id,geometry:new Ti(i,Li({xSize:.5,ySize:.5,zSize:.001})),material:new Ni(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ji(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Vi(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Vi(i,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});var n=$.vec3([0,0,0]),o=$.vec3(),a=$.vec3([0,0,1]),l=$.vec4(4),u=$.vec3(),A=function(){var e=r._sectionPlane.scene.center,t=[-r._sectionPlane.dir[0],-r._sectionPlane.dir[1],-r._sectionPlane.dir[2]];$.subVec3(e,r._sectionPlane.pos,n);var i=-$.dotVec3(t,n);$.normalizeVec3(t),$.mulVec3Scalar(t,i,o);var s=$.vec3PairToQuaternion(a,r._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],r._mesh.quaternion=s,r._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",A),this._onSectionPlaneDir=this._sectionPlane.on("dir",A),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),kE=function(){function e(t,i){var s=this;if(x(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new $i(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new bi(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;var r=this._scene.camera,n=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),o=$.vec3(),a=$.vec3(),l=$.vec3();this._synchCamera=function(){var e=s._viewer.camera.eye,t=s._viewer.camera.look,i=s._viewer.camera.up;$.mulVec3Scalar($.normalizeVec3($.subVec3(e,t,o)),7),s._zUp?($.transformVec3(n,o,a),$.transformVec3(n,i,l),r.look=[0,0,0],r.eye=$.transformVec3(n,o,a),r.up=$.transformPoint3(n,i,l)):(r.look=[0,0,0],r.eye=o,r.up=i)},this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",(function(e){s._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=s._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)s._planes[u.id]&&s._onHoverLeavePlane(u.id);u=t.entity,s._planes[u.id]&&s._onHoverEnterPlane(u.id)}}else u&&(s._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?s._planes[u.id]&&s._onClickedPlane(u.id):s._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(s._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new FE(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}]),e}(),IE=$.AABB3(),DE=$.vec3(),SE=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,"SectionPlanes",e))._freeControls=[],s._sectionPlanes=e.scene.sectionPlanes,s._controls={},s._shownControlId=null,null!==r.overviewCanvasId&&void 0!==r.overviewCanvasId){var n=document.getElementById(r.overviewCanvasId);n?s._overview=new kE(b(s),{overviewCanvas:n,visible:r.overviewVisible,onHoverEnterPlane:function(e){s._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){s._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(s.getShownControl()!==e){s.showControl(e);var t=s.sectionPlanes[e].pos;IE.set(s.viewer.scene.aabb),$.getAABB3Center(IE,DE),IE[0]+=t[0]-DE[0],IE[1]+=t[1]-DE[1],IE[2]+=t[2]-DE[2],IE[3]+=t[0]-DE[0],IE[4]+=t[1]-DE[1],IE[5]+=t[2]-DE[2],s.viewer.cameraFlight.flyTo({aabb:IE,fitFOV:65})}else s.hideControl()},onClickedNothing:function(){s.hideControl()}}):s.warn("Can't find overview canvas: '"+r.overviewCanvasId+"' - will create plugin without overview")}return s._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){s._sectionPlaneCreated(e)})),s}return C(i,[{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=new hn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new EE(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}},{key:"destroySectionPlane",value:function(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"StoreyViews",e))._objectsMemento=new Ad,s._cameraMemento=new od,s.storeys={},s.modelStoreys={},s._fitStoreyMaps=!!r.fitStoreyMaps,s._onModelLoaded=s.viewer.scene.on("modelLoaded",(function(e){s._registerModelStoreys(e),s.fire("storeys",s.storeys)})),s}return C(i,[{key:"_registerModelStoreys",value:function(e){var t=this,i=this.viewer,s=i.scene,r=i.metaScene,n=r.metaModels[e],o=s.models[e];if(n&&n.rootMetaObjects)for(var a=n.rootMetaObjects,l=0,u=a.length;l.5?p.length:0,g=new TE(this,o.aabb,f,e,d,v);g._onModelDestroyed=o.once("destroyed",(function(){t._deregisterModelStoreys(e),t.fire("storeys",t.storeys)})),this.storeys[d]=g,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][d]=g}}},{key:"_deregisterModelStoreys",value:function(e){var t=this.modelStoreys[e];if(t){var i=this.viewer.scene;for(var s in t)if(t.hasOwnProperty(s)){var r=t[s],n=i.models[r.modelId];n&&n.off(r._onModelDestroyed),delete this.storeys[s]}delete this.modelStoreys[e]}}},{key:"fitStoreyMaps",get:function(){return this._fitStoreyMaps}},{key:"gotoStoreyCamera",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());var s=this.viewer,r=s.scene,n=r.camera,o=i.storeyAABB;if(o[3]1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(i){var s=this.viewer,r=s.scene,n=s.metaScene,o=n.metaObjects[e];o&&(t.hideOthers&&r.setObjectsVisible(s.scene.visibleObjectIds,!1),this.withStoreyObjects(e,(function(e,t){e&&(e.visible=!0)})))}else this.error("IfcBuildingStorey not found with this ID: "+e)}},{key:"withStoreyObjects",value:function(e,t){var i=this.viewer,s=i.scene,r=i.metaScene,n=r.metaObjects[e];if(n)for(var o=n.getObjectIDsInSubtree(),a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),OE;var s,r,n=this.viewer,o=n.scene,a=t.format||"png",l=this._fitStoreyMaps?i.storeyAABB:i.modelAABB,u=Math.abs((l[5]-l[2])/(l[3]-l[0])),A=t.padding||0;t.width&&t.height?(s=t.width,r=t.height):t.height?(r=t.height,s=Math.round(r/u)):t.width?(s=t.width,r=Math.round(s*u)):(s=300,r=Math.round(s*u)),this._objectsMemento.saveObjects(o),this._cameraMemento.saveCamera(o),this.showStoreyObjects(e,le.apply(t,{hideOthers:!0})),this._arrangeStoreyMapCamera(i);var c=n.getSnapshot({width:s,height:r,format:a});return this._objectsMemento.restoreObjects(o),this._cameraMemento.restoreCamera(o),new LE(e,c,a,s,r,A)}},{key:"_arrangeStoreyMapCamera",value:function(e){var t=this.viewer,i=t.scene.camera,s=this._fitStoreyMaps?e.storeyAABB:e.modelAABB,r=$.getAABB3Center(s),n=RE;n[0]=r[0]+.5*i.worldUp[0],n[1]=r[1]+.5*i.worldUp[1],n[2]=r[2]+.5*i.worldUp[2];var o=i.worldForward;t.cameraFlight.jumpTo({eye:n,look:r,up:o});var a=(s[3]-s[0])/2,l=(s[4]-s[1])/2,u=(s[5]-s[2])/2,A=-a,c=+a,h=-l,d=+l,p=-u,f=+u;t.camera.customProjection.matrix=$.orthoMat4c(A,c,p,f,h,d,UE),t.camera.projection="customProjection"}},{key:"pickStoreyMap",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),null;var n=1-t[0]/e.width,o=1-t[1]/e.height,a=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,l=a[0],u=a[1],A=a[2],c=a[3],h=a[4],d=a[5],p=c-l,f=h-u,v=d-A,g=$.vec3([l+p*n,u+.5*f,A+v*o]),m=$.vec3([0,-1,0]),_=$.addVec3(g,m,RE),y=this.viewer.camera.worldForward,b=$.lookAtMat4v(g,_,y,UE),w=this.viewer.scene.pick({pickSurface:i.pickSurface,pickInvisible:!0,matrix:b});return w}},{key:"storeyMapToWorldPos",value:function(e,t){var i=e.storeyId,s=this.storeys[i];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+i),null;var r=1-t[0]/e.width,n=1-t[1]/e.height,o=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,a=o[0],l=o[1],u=o[2],A=o[3],c=o[4],h=o[5],d=A-a,p=c-l,f=h-u,v=$.vec3([a+d*r,l+.5*p,u+f*n]);return v}},{key:"getStoreyContainingWorldPos",value:function(e){for(var t in this.storeys){var i=this.storeys[t];if($.point3AABB3Intersect(i.storeyAABB,e))return t}return null}},{key:"worldPosToStoreyMap",value:function(e,t,i){var s=e.storeyId,r=this.storeys[s];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+s),!1;var n=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,o=n[0],a=n[1],l=n[2],u=n[3]-o,A=n[4]-a,c=n[5]-l,h=this.viewer.camera.worldUp,d=h[0]>h[1]&&h[0]>h[2],p=!d&&h[1]>h[0]&&h[1]>h[2];!d&&!p&&h[2]>h[0]&&(h[2],h[1]);var f=e.width/u,v=p?e.height/c:e.height/A;return i[0]=Math.floor(e.width-(t[0]-o)*f),i[1]=Math.floor(e.height-(t[2]-l)*v),i[0]>=0&&i[0]=0&&i[1]<=e.height}},{key:"worldDirToStoreyMap",value:function(e,t,i){var s=this.viewer.camera,r=s.eye,n=s.look,o=$.subVec3(n,r,RE),a=s.worldUp,l=a[0]>a[1]&&a[0]>a[2],u=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!u&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=o[1],i[1]=o[2]):u?(i[0]=o[0],i[1]=o[2]):(i[0]=o[0],i[1]=o[1]),$.normalizeVec2(i)}},{key:"destroy",value:function(){this.viewer.scene.off(this._onModelLoaded),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),QE=new Float64Array([0,0,1]),VE=new Float64Array(4),HE=function(){function e(t){x(this,e),this.id=null,this._viewer=t.viewer,this._plugin=t,this._visible=!1,this._pos=$.vec3(),this._origin=$.vec3(),this._rtcPos=$.vec3(),this._baseDir=$.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),Re(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=$.vec3PairToQuaternion(QE,e,VE)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new wn(t,{position:[0,0,0],scale:[5,5,5]});var s=this._rootNode,r={arrowHead:new Ti(s,an({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ti(s,an({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Ti(s,an({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},n={red:new Ni(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new Ni(s,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new Ni(s,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Vi(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:s.addChild(new nn(s,{geometry:new Ti(s,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new Ni(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new nn(s,{geometry:new Ti(s,Jn({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:s.addChild(new nn(s,{geometry:new Ti(s,ln({radius:.05})),material:n.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new nn(s,{geometry:r.arrowHead,material:n.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new nn(s,{geometry:r.axis,material:n.blue,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new nn(s,{geometry:new Ti(s,Jn({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Vi(s,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),e),zAxisArrow:s.addChild(new nn(s,{geometry:r.arrowHeadBig,material:n.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this._rootNode,i=$.vec2(),s=this._viewer.camera,r=this._viewer.scene,n=0,o=!1,a=$.vec3([0,0,0]),l=-1;this._onCameraViewMatrix=r.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=r.camera.on("projMatrix",(function(){})),this._onSceneTick=r.on("tick",(function(){o=!1;var i=Math.abs($.lenVec3($.subVec3(r.camera.eye,e._pos,a)));if(i!==l&&"perspective"===s.projection){var u=.07*(Math.tan(s.perspective.fov*$.DEGTORAD)*i);t.scale=[u,u,u],l=i}if("ortho"===s.projection){var c=s.ortho.scale/10;t.scale=[c,c,c],l=i}0!==n&&(A(n),n=0)}));var u=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),A=function(t){var i=e._sectionPlane.pos,s=e._sectionPlane.dir;$.addVec3(i,$.mulVec3Scalar(s,.1*t*e._plugin.getDragSensitivity(),$.vec3())),e._sectionPlane.pos=i},c=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){c=!0;var s=u(t);i[0]=s[0],i[1]=s[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&c&&!o){var s=u(t),r=s[0],n=s[1];A(n-i[1]),i[0]=r,i[1]=n}}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,c&&(t.which,c=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=function(t){e._visible&&(n+=Math.max(-1,Math.min(1,40*-t.deltaY)))});var h,d,p=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=t.touches[0].clientY,p=h,n=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(o||(o=!0,d=t.touches[0].clientY,null!==p&&(n+=d-p),p=d))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=null,d=null,n=0)})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.removeEventListener("touchstart",this._handleTouchStart),r.removeEventListener("touchmove",this._handleTouchMove),r.removeEventListener("touchend",this._handleTouchEnd),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),jE=function(){function e(t,i,s){var r=this;x(this,e),this.id=s.id,this._sectionPlane=s,this._mesh=new nn(i,{id:s.id,geometry:new Ti(i,Li({xSize:.5,ySize:.5,zSize:.001})),material:new Ni(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ji(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Vi(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Vi(i,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});var n=$.vec3([0,0,0]),o=$.vec3(),a=$.vec3([0,0,1]),l=$.vec4(4),u=$.vec3(),A=function(){var e=r._sectionPlane.scene.center,t=[-r._sectionPlane.dir[0],-r._sectionPlane.dir[1],-r._sectionPlane.dir[2]];$.subVec3(e,r._sectionPlane.pos,n);var i=-$.dotVec3(t,n);$.normalizeVec3(t),$.mulVec3Scalar(t,i,o);var s=$.vec3PairToQuaternion(a,r._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],r._mesh.quaternion=s,r._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",A),this._onSectionPlaneDir=this._sectionPlane.on("dir",A),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),GE=function(){function e(t,i){var s=this;if(x(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new $i(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new bi(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;var r=this._scene.camera,n=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),o=$.vec3(),a=$.vec3(),l=$.vec3();this._synchCamera=function(){var e=s._viewer.camera.eye,t=s._viewer.camera.look,i=s._viewer.camera.up;$.mulVec3Scalar($.normalizeVec3($.subVec3(e,t,o)),7),s._zUp?($.transformVec3(n,o,a),$.transformVec3(n,i,l),r.look=[0,0,0],r.eye=$.transformVec3(n,o,a),r.up=$.transformPoint3(n,i,l)):(r.look=[0,0,0],r.eye=o,r.up=i)},this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",(function(e){s._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=s._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)s._planes[u.id]&&s._onHoverLeavePlane(u.id);u=t.entity,s._planes[u.id]&&s._onHoverEnterPlane(u.id)}}else u&&(s._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?s._planes[u.id]&&s._onClickedPlane(u.id):s._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(s._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new jE(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}]),e}(),zE=$.AABB3(),WE=$.vec3(),KE=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,"FaceAlignedSectionPlanesPlugin",e))._freeControls=[],s._sectionPlanes=e.scene.sectionPlanes,s._controls={},s._shownControlId=null,s._dragSensitivity=r.dragSensitivity||1,null!==r.overviewCanvasId&&void 0!==r.overviewCanvasId){var n=document.getElementById(r.overviewCanvasId);n?s._overview=new GE(b(s),{overviewCanvas:n,visible:r.overviewVisible,onHoverEnterPlane:function(e){s._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){s._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(s.getShownControl()!==e){s.showControl(e);var t=s.sectionPlanes[e].pos;zE.set(s.viewer.scene.aabb),$.getAABB3Center(zE,WE),zE[0]+=t[0]-WE[0],zE[1]+=t[1]-WE[1],zE[2]+=t[2]-WE[2],zE[3]+=t[0]-WE[0],zE[4]+=t[1]-WE[1],zE[5]+=t[2]-WE[2],s.viewer.cameraFlight.flyTo({aabb:zE,fitFOV:65})}else s.hideControl()},onClickedNothing:function(){s.hideControl()}}):s.warn("Can't find overview canvas: '"+r.overviewCanvasId+"' - will create plugin without overview")}return null===r.controlElementId||void 0===r.controlElementId?s.error("Parameter expected: controlElementId"):(s._controlElement=document.getElementById(r.controlElementId),s._controlElement||s.warn("Can't find control element: '"+r.controlElementId+"' - will create plugin without control element")),s._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){s._sectionPlaneCreated(e)})),s}return C(i,[{key:"setDragSensitivity",value:function(e){this._dragSensitivity=e||1}},{key:"getDragSensitivity",value:function(){return this._dragSensitivity}},{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=new hn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new HE(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}},{key:"destroySectionPlane",value:function(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getSTL",value:function(e,t,i){e=this._cacheBusterURL(e);var s=new XMLHttpRequest;s.overrideMimeType("application/json"),s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i(s.statusText))},s.send(null)}}]),e}(),JE=$.vec3(),ZE=function(){function e(){x(this,e)}return C(e,[{key:"load",value:function(e,t,i,s,r,n){s=s||{};var o=e.viewer.scene.canvas.spinner;o.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,s){try{var r=sF(i);qE(r)?$E(e,r,t,s):eF(e,iF(i),t,s)}catch(e){t.fire("error",e)}}(e,t,i,s);try{var a=sF(i);qE(a)?$E(e,a,t,s):eF(e,iF(i),t,s),o.processes--,_e.scheduleTask((function(){t.fire("loaded",!0,!1)})),r&&r()}catch(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}}),(function(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}))}},{key:"parse",value:function(e,t,i,s){var r=e.viewer.scene.canvas.spinner;r.processes++;try{var n=sF(i);qE(n)?$E(e,n,t,s):eF(e,iF(i),t,s),r.processes--,_e.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){r.processes--,t.fire("error",e)}}}]),e}();function qE(e){var t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;for(var i=[115,111,108,105,100],s=0;s<5;s++)if(i[s]!==t.getUint8(s,!1))return!0;return!1}function $E(e,t,i,s){for(var r,n,o,a,l,u,A,c=new DataView(t),h=c.getUint32(80,!0),d=!1,p=null,f=null,v=null,g=!1,m=0;m<70;m++)1129270351===c.getUint32(m,!1)&&82===c.getUint8(m+4)&&61===c.getUint8(m+5)&&(d=!0,a=[],l=c.getUint8(m+6)/255,u=c.getUint8(m+7)/255,A=c.getUint8(m+8)/255,c.getUint8(m+9));for(var _=new Cn(i,{roughness:.5}),y=[],b=[],w=s.splitMeshes,B=0;B>5&31)/31,o=(E>>10&31)/31):(r=l,n=u,o=A),(w&&r!==p||n!==f||o!==v)&&(null!==p&&(g=!0),p=r,f=n,v=o)}for(var F=1;F<=3;F++){var k=x+12*F;y.push(c.getFloat32(k,!0)),y.push(c.getFloat32(k+4,!0)),y.push(c.getFloat32(k+8,!0)),b.push(P,C,M),d&&a.push(r,n,o,1)}w&&g&&(tF(i,y,b,a,_,s),y=[],b=[],a=a?[]:null,g=!1)}y.length>0&&tF(i,y,b,a,_,s)}function eF(e,t,i,s){for(var r,n,o,a,l,u,A,c=/facet([\s\S]*?)endfacet/g,h=0,d=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,p=new RegExp("vertex"+d+d+d,"g"),f=new RegExp("normal"+d+d+d,"g"),v=[],g=[];null!==(a=c.exec(t));){for(l=0,u=0,A=a[0];null!==(a=f.exec(A));)r=parseFloat(a[1]),n=parseFloat(a[2]),o=parseFloat(a[3]),u++;for(;null!==(a=p.exec(A));)v.push(parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3])),g.push(r,n,o),l++;1!==u&&e.error("Error in normal of face "+h),3!==l&&e.error("Error in positions of face "+h),h++}tF(i,v,g,null,new Cn(i,{roughness:.5}),s)}function tF(e,t,i,s,r,n){for(var o=new Int32Array(t.length/3),a=0,l=o.length;a0?i:null,s=s&&s.length>0?s:null,n.smoothNormals&&$.faceToVertexNormals(t,i,n);var u=JE;Ue(t,t,u);var A=new Ti(e,{primitive:"triangles",positions:t,normals:i,colors:s,indices:o}),c=new nn(e,{origin:0!==u[0]||0!==u[1]||0!==u[2]?u:null,geometry:A,material:r,edges:n.edges});e.addChild(c)}function iF(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0,s=e.length;i1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"STLLoader",e,r))._sceneGraphLoader=new ZE,s.dataSource=r.dataSource,s}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new YE}},{key:"load",value:function(e){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new wn(this.viewer.scene,le.apply(e,{isModel:!0})),i=e.src,s=e.stl;return i||s?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,s,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}}]),i}(),nF=function(){function e(){x(this,e)}return C(e,[{key:"createRootNode",value:function(){return document.createElement("ul")}},{key:"createNodeElement",value:function(e,t,i,s,r){var n=document.createElement("li");if(n.id=e.nodeId,e.xrayed&&n.classList.add("xrayed-node"),e.children.length>0){var o=document.createElement("a");o.href="#",o.id="switch-".concat(e.nodeId),o.textContent="+",o.classList.add("plus"),t&&o.addEventListener("click",t),n.appendChild(o)}var a=document.createElement("input");a.id="checkbox-".concat(e.nodeId),a.type="checkbox",a.checked=e.checked,a.style["pointer-events"]="all",i&&a.addEventListener("change",i),n.appendChild(a);var l=document.createElement("span");return l.textContent=e.title,n.appendChild(l),s&&(l.oncontextmenu=s),r&&(l.onclick=r),n}},{key:"createDisabledNodeElement",value:function(e){var t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);var s=document.createElement("span");return s.textContent=e,t.appendChild(s),t}},{key:"addChildren",value:function(e,t){var i=document.createElement("ul");t.forEach((function(e){i.appendChild(e)})),e.parentElement.appendChild(i)}},{key:"expand",value:function(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}},{key:"collapse",value:function(e,t,i){if(e){var s=e.parentElement;if(s){var r=s.querySelector("ul");r&&(s.removeChild(r),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}}}},{key:"isExpanded",value:function(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}},{key:"getId",value:function(e){return e.parentElement.id}},{key:"getIdFromCheckbox",value:function(e){return e.id.replace("checkbox-","")}},{key:"getSwitchElement",value:function(e){return document.getElementById("switch-".concat(e))}},{key:"isChecked",value:function(e){return e.checked}},{key:"setCheckbox",value:function(e,t){var i=document.getElementById("checkbox-".concat(e));i&&t!==i.checked&&(i.checked=t)}},{key:"setXRayed",value:function(e,t){var i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}},{key:"setHighlighted",value:function(e,t){var i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}]),e}(),oF=[],aF=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(s=t.call(this,"TreeViewPlugin",e)).errors=[],s.valid=!0;var n=r.containerElement||document.getElementById(r.containerElementId);if(!(n instanceof HTMLElement))return s.error("Mandatory config expected: valid containerElementId or containerElement"),y(s);for(var o=0;;o++)if(!oF[o]){oF[o]=b(s),s._index=o,s._id="tree-".concat(o);break}if(s._containerElement=n,s._metaModels={},s._autoAddModels=!1!==r.autoAddModels,s._autoExpandDepth=r.autoExpandDepth||0,s._sortNodes=!1!==r.sortNodes,s._viewer=e,s._rootElement=null,s._muteSceneEvents=!1,s._muteTreeEvents=!1,s._rootNodes=[],s._objectNodes={},s._nodeNodes={},s._rootNames={},s._sortNodes=r.sortNodes,s._pruneEmptyNodes=r.pruneEmptyNodes,s._showListItemElementId=null,s._renderService=r.renderService||new nF,!s._renderService)throw new Error("TreeViewPlugin: no render service set");if(s._containerElement.oncontextmenu=function(e){e.preventDefault()},s._onObjectVisibility=s._viewer.scene.on("objectVisibility",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){var r=e.visible;if(r!==i.checked){s._muteTreeEvents=!0,i.checked=r,r?i.numVisibleEntities++:i.numVisibleEntities--,s._renderService.setCheckbox(i.nodeId,r);for(var n=i.parent;n;)n.checked=r,r?n.numVisibleEntities++:n.numVisibleEntities--,s._renderService.setCheckbox(n.nodeId,n.numVisibleEntities>0),n=n.parent;s._muteTreeEvents=!1}}}})),s._onObjectXrayed=s._viewer.scene.on("objectXRayed",(function(e){if(!s._muteSceneEvents){var t=e.id,i=s._objectNodes[t];if(i){s._muteTreeEvents=!0;var r=e.xrayed;r!==i.xrayed&&(i.xrayed=r,s._renderService.setXRayed(i.nodeId,r),s._muteTreeEvents=!1)}}})),s._switchExpandHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._expandSwitchElement(t)},s._switchCollapseHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;s._collapseSwitchElement(t)},s._checkboxChangeHandler=function(e){if(!s._muteTreeEvents){s._muteSceneEvents=!0;var t=e.target,i=s._renderService.isChecked(t),r=s._renderService.getIdFromCheckbox(t),n=s._nodeNodes[r],o=s._viewer.scene.objects,a=0;s._withNodeTree(n,(function(e){var t=e.objectId,r=o[t],n=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,n&&i!==e.checked&&a++,e.checked=i,s._renderService.setCheckbox(e.nodeId,i),r&&(r.visible=i)}));for(var l=n.parent;l;)l.checked=i,i?l.numVisibleEntities+=a:l.numVisibleEntities-=a,s._renderService.setCheckbox(l.nodeId,l.numVisibleEntities>0),l=l.parent;s._muteSceneEvents=!1}},s._hierarchy=r.hierarchy||"containment",s._autoExpandDepth=r.autoExpandDepth||0,s._autoAddModels){for(var a=Object.keys(s.viewer.metaScene.metaModels),l=0,u=a.length;l1&&void 0!==arguments[1]?arguments[1]:{};if(this._containerElement){var s=this.viewer.scene.models[e];if(!s)throw"Model not found: "+e;var r=this.viewer.metaScene.metaModels[e];r?this._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=r,i&&i.rootName&&(this._rootNames[e]=i.rootName),s.on("destroyed",(function(){t.removeModel(s.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}}},{key:"removeModel",value:function(e){this._containerElement&&(this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes()))}},{key:"showNode",value:function(e){this.unShowNode();var t=this._objectNodes[e];if(t){var i=t.nodeId,s=this._renderService.getSwitchElement(i);if(s)return this._expandSwitchElement(s),s.scrollIntoView(),!0;var r=[];r.unshift(t);for(var n=t.parent;n;)r.unshift(n),n=n.parent;for(var o=0,a=r.length;o0;return this.valid}},{key:"_validateMetaModelForStoreysHierarchy",value:function(){return!0}},{key:"_createEnabledNodes",value:function(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}},{key:"_createDisabledNodes",value:function(){var e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);var t=this._viewer.metaScene.rootMetaObjects;for(var i in t){var s=t[i],r=s.type,n=s.name,o=n&&""!==n&&"Undefined"!==n&&"Default"!==n?n:r,a=this._renderService.createDisabledNodeElement(o);e.appendChild(a)}}},{key:"_findEmptyNodes",value:function(){var e=this._viewer.metaScene.rootMetaObjects;for(var t in e)this._findEmptyNodes2(e[t])}},{key:"_findEmptyNodes2",value:function(e){var t=this.viewer,i=t.scene,s=e.children,r=e.id,n=i.objects[r];if(e._countEntities=0,n&&e._countEntities++,s)for(var o=0,a=s.length;or.aabb[n]?-1:e.aabb[n]s?1:0}},{key:"_synchNodesToEntities",value:function(){for(var e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects,s=0,r=e.length;s0){for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"ViewCull",e))._objectCullStates=AF(e.scene),s._maxTreeDepth=r.maxTreeDepth||8,s._modelInfos={},s._frustum=new Me,s._kdRoot=null,s._frustumDirty=!1,s._kdTreeDirty=!1,s._onViewMatrix=e.scene.camera.on("viewMatrix",(function(){s._frustumDirty=!0})),s._onProjMatrix=e.scene.camera.on("projMatMatrix",(function(){s._frustumDirty=!0})),s._onModelLoaded=e.scene.on("modelLoaded",(function(e){var t=s.viewer.scene.models[e];t&&s._addModel(t)})),s._onSceneTick=e.scene.on("tick",(function(){s._doCull()})),s}return C(i,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"_addModel",value:function(e){var t=this,i={model:e,onDestroyed:e.on("destroyed",(function(){t._removeModel(e)}))};this._modelInfos[e.id]=i,this._kdTreeDirty=!0}},{key:"_removeModel",value:function(e){var t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}},{key:"_doCull",value:function(){var e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){var t=this._kdRoot;t&&this._visitKDNode(t)}}},{key:"_buildFrustum",value:function(){var e=this.viewer.scene.camera;Ee(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}},{key:"_buildKDTree",value:function(){var e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:Me.INTERSECT};for(var t=0,i=this._objectCullStates.numObjects;t=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void $.expandAABB3(e.aabb,r);if(e.left&&$.containsAABB3(e.left.aabb,r))this._insertEntityIntoKDTree(e.left,t,i,s+1);else if(e.right&&$.containsAABB3(e.right.aabb,r))this._insertEntityIntoKDTree(e.right,t,i,s+1);else{var n=e.aabb;cF[0]=n[3]-n[0],cF[1]=n[4]-n[1],cF[2]=n[5]-n[2];var o=0;if(cF[1]>cF[o]&&(o=1),cF[2]>cF[o]&&(o=2),!e.left){var a=n.slice();if(a[o+3]=(n[o]+n[o+3])/2,e.left={aabb:a,intersection:Me.INTERSECT},$.containsAABB3(a,r))return void this._insertEntityIntoKDTree(e.left,t,i,s+1)}if(!e.right){var l=n.slice();if(l[o]=(n[o]+n[o+3])/2,e.right={aabb:l,intersection:Me.INTERSECT},$.containsAABB3(l,r))return void this._insertEntityIntoKDTree(e.right,t,i,s+1)}e.objects=e.objects||[],e.objects.push(i),$.expandAABB3(e.aabb,r)}}},{key:"_visitKDNode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(t===Me.INTERSECT||e.intersects!==t){t===Me.INTERSECT&&(t=Fe(this._frustum,e.aabb),e.intersects=t);var i=t===Me.OUTSIDE,s=e.objects;if(s&&s.length>0)for(var r=0,n=s.length;r0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getManifest",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getMetaModel",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getXKT",value:function(e,t,i){var s=function(){};t=t||s,i=i||s;var r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){var n=!!r[2],o=r[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u=0;)e[t]=0}var i=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),s=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),r=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);t(o);var a=new Array(60);t(a);var l=new Array(512);t(l);var u=new Array(256);t(u);var A=new Array(29);t(A);var c,h,d,p=new Array(30);function f(e,t,i,s,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=s,this.max_length=r,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(p);var g=function(e){return e<256?l[e]:l[256+(e>>>7)]},m=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},_=function(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1},w=function(e,t,i){var s,r,n=new Array(16),o=0;for(s=1;s<=15;s++)o=o+i[s-1]<<1,n[s]=o;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=b(n[a]++,a))}},x=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},P=function(e){e.bi_valid>8?m(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,i,s){var r=2*t,n=2*i;return e[r]>1;i>=1;i--)M(e,n,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],M(e,n,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,n[2*r]=n[2*i]+n[2*s],e.depth[r]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,n[2*i+1]=n[2*s+1]=r,e.heap[1]=r++,M(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,s,r,n,o,a,l=t.dyn_tree,u=t.max_code,A=t.stat_desc.static_tree,c=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,f=0;for(n=0;n<=15;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(n=l[2*l[2*(s=e.heap[i])+1]+1]+1)>p&&(n=p,f++),l[2*s+1]=n,s>u||(e.bl_count[n]++,o=0,s>=d&&(o=h[s-d]),a=l[2*s],e.opt_len+=a*(n+o),c&&(e.static_len+=a*(A[2*s+1]+o)));if(0!==f){do{for(n=p-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[p]--,f-=2}while(f>0);for(n=p;0!==n;n--)for(s=e.bl_count[n];0!==s;)(r=e.heap[--i])>u||(l[2*r+1]!==n&&(e.opt_len+=(n-l[2*r+1])*l[2*r],l[2*r+1]=n),s--)}}(e,t),w(n,u,e.bl_count)},k=function(e,t,i){var s,r,n=-1,o=t[1],a=0,l=7,u=4;for(0===o&&(l=138,u=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=o,o=t[2*(s+1)+1],++a>=7;v<30;v++)for(p[v]=g<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),F(e,e.l_desc),F(e,e.d_desc),u=function(e){var t;for(k(e,e.dyn_ltree,e.l_desc.max_code),k(e,e.dyn_dtree,e.d_desc.max_code),F(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*n[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(l=e.static_len+3+7>>>3)<=r&&(r=l)):r=l=i+5,i+4<=r&&-1!==t?S(e,t,i,s):4===e.strategy||l===r?(_(e,2+(s?1:0),3),E(e,o,a)):(_(e,4+(s?1:0),3),function(e,t,i,s){var r;for(_(e,t-257,5),_(e,i-1,5),_(e,s-4,4),r=0;r>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*g(t)]++),e.sym_next===e.sym_end},O=function(e){_(e,2,3),y(e,256,o),function(e){16===e.bi_valid?(m(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)},N=function(e,t,i,s){for(var r=65535&e|0,n=e>>>16&65535|0,o=0;0!==i;){i-=o=i>2e3?2e3:i;do{n=n+(r=r+t[s++]|0)|0}while(--o);r%=65521,n%=65521}return r|n<<16|0},Q=new Uint32Array(function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}()),V=function(e,t,i,s){var r=Q,n=s+i;e^=-1;for(var o=s;o>>8^r[255&(e^t[o])];return-1^e},H={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},j={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},G=T,z=L,W=R,K=U,X=O,Y=j.Z_NO_FLUSH,J=j.Z_PARTIAL_FLUSH,Z=j.Z_FULL_FLUSH,q=j.Z_FINISH,$=j.Z_BLOCK,ee=j.Z_OK,te=j.Z_STREAM_END,ie=j.Z_STREAM_ERROR,se=j.Z_DATA_ERROR,re=j.Z_BUF_ERROR,ne=j.Z_DEFAULT_COMPRESSION,oe=j.Z_FILTERED,ae=j.Z_HUFFMAN_ONLY,le=j.Z_RLE,ue=j.Z_FIXED,Ae=j.Z_UNKNOWN,ce=j.Z_DEFLATED,he=258,de=262,pe=42,fe=113,ve=666,ge=function(e,t){return e.msg=H[t],t},me=function(e){return 2*e-(e>4?9:0)},_e=function(e){for(var t=e.length;--t>=0;)e[t]=0},ye=function(e){var t,i,s,r=e.w_size;s=t=e.hash_size;do{i=e.head[--s],e.head[s]=i>=r?i-r:0}while(--t);s=t=r;do{i=e.prev[--s],e.prev[s]=i>=r?i-r:0}while(--t)},be=function(e,t,i){return(t<e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Be=function(e,t){W(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,we(e.strm)},xe=function(e,t){e.pending_buf[e.pending++]=t},Pe=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,i,s){var r=e.avail_in;return r>s&&(r=s),0===r?0:(e.avail_in-=r,t.set(e.input.subarray(e.next_in,e.next_in+r),i),1===e.state.wrap?e.adler=N(e.adler,t,r,i):2===e.state.wrap&&(e.adler=V(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)},Me=function(e,t){var i,s,r=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-de?e.strstart-(e.w_size-de):0,u=e.window,A=e.w_mask,c=e.prev,h=e.strstart+he,d=u[n+o-1],p=u[n+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(i=t)+o]===p&&u[i+o-1]===d&&u[i]===u[n]&&u[++i]===u[n+1]){n+=2,i++;do{}while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&no){if(e.match_start=t,o=s,s>=a)break;d=u[n+o-1],p=u[n+o]}}}while((t=c[t&A])>l&&0!=--r);return o<=e.lookahead?o:e.lookahead},Ee=function(e){var t,i,s,r=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=r+(r-de)&&(e.window.set(e.window.subarray(r,r+r-i),0),e.match_start-=r,e.strstart-=r,e.block_start-=r,e.insert>e.strstart&&(e.insert=e.strstart),ye(e),i+=r),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=t,e.lookahead+e.insert>=3)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=be(e,e.ins_h,e.window[s+1]);e.insert&&(e.ins_h=be(e,e.ins_h,e.window[s+3-1]),e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookaheade.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,r=e.bi_valid+42>>3,e.strm.avail_out(s=e.strstart-e.block_start)+e.strm.avail_in&&(i=s+e.strm.avail_in),i>r&&(i=r),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,we(e.strm),s&&(s>i&&(s=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+s),e.strm.next_out),e.strm.next_out+=s,e.strm.avail_out-=s,e.strm.total_out+=s,e.block_start+=s,i-=s),i&&(Ce(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return(a-=e.strm.avail_in)&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waterr&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,r+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),r>e.strm.avail_in&&(r=e.strm.avail_in),r&&(Ce(e.strm,e.window,e.strstart,r),e.strstart+=r,e.insert+=r>e.w_size-e.insert?e.w_size-e.insert:r),e.high_water>3,n=(r=e.pending_buf_size-r>65535?65535:e.pending_buf_size-r)>e.w_size?e.w_size:r,((s=e.strstart-e.block_start)>=n||(s||t===q)&&t!==Y&&0===e.strm.avail_in&&s<=r)&&(i=s>r?r:s,o=t===q&&0===e.strm.avail_in&&i===s?1:0,z(e,e.block_start,i,o),e.block_start+=i,we(e.strm)),o?3:1)},ke=function(e,t){for(var i,s;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-de&&(e.match_length=Me(e,i)),e.match_length>=3)if(s=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=be(e,e.ins_h,e.window[e.strstart+1]);else s=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var i,s,r;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,s&&(Be(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((s=K(e,0,e.window[e.strstart-1]))&&Be(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2};function De(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}var Se=[new De(0,0,0,0,Fe),new De(4,4,8,4,ke),new De(4,5,16,8,ke),new De(4,6,32,32,ke),new De(4,4,16,16,Ie),new De(8,16,32,32,Ie),new De(8,16,128,128,Ie),new De(8,32,128,256,Ie),new De(32,128,258,1024,Ie),new De(32,258,258,4096,Ie)];function Te(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ce,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),_e(this.dyn_ltree),_e(this.dyn_dtree),_e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),_e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),_e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Le=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==pe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==fe&&t.status!==ve?1:0},Re=function(e){if(Le(e))return ge(e,ie);e.total_in=e.total_out=0,e.data_type=Ae;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?pe:fe,e.adler=2===t.wrap?0:1,t.last_flush=-2,G(t),ee},Ue=function(e){var t,i=Re(e);return i===ee&&((t=e.state).window_size=2*t.w_size,_e(t.head),t.max_lazy_match=Se[t.level].max_lazy,t.good_match=Se[t.level].good_length,t.nice_match=Se[t.level].nice_length,t.max_chain_length=Se[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i},Oe=function(e,t,i,s,r,n){if(!e)return ie;var o=1;if(t===ne&&(t=6),s<0?(o=0,s=-s):s>15&&(o=2,s-=16),r<1||r>9||i!==ce||s<8||s>15||t<0||t>9||n<0||n>ue||8===s&&1!==o)return ge(e,ie);8===s&&(s=9);var a=new Te;return e.state=a,a.strm=e,a.status=pe,a.wrap=o,a.gzhead=null,a.w_bits=s,a.w_size=1<$||t<0)return e?ge(e,ie):ie;var i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ve&&t!==q)return ge(e,0===e.avail_out?re:ie);var s=i.last_flush;if(i.last_flush=t,0!==i.pending){if(we(e),0===e.avail_out)return i.last_flush=-1,ee}else if(0===e.avail_in&&me(t)<=me(s)&&t!==q)return ge(e,re);if(i.status===ve&&0!==e.avail_in)return ge(e,re);if(i.status===pe&&0===i.wrap&&(i.status=fe),i.status===pe){var r=ce+(i.w_bits-8<<4)<<8;if(r|=(i.strategy>=ae||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(r|=32),Pe(i,r+=31-r%31),0!==i.strstart&&(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),e.adler=1,i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee}if(57===i.status)if(e.adler=0,xe(i,31),xe(i,139),xe(i,8),i.gzhead)xe(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),xe(i,255&i.gzhead.time),xe(i,i.gzhead.time>>8&255),xe(i,i.gzhead.time>>16&255),xe(i,i.gzhead.time>>24&255),xe(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),xe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(xe(i,255&i.gzhead.extra.length),xe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=V(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(xe(i,0),xe(i,0),xe(i,0),xe(i,0),xe(i,0),xe(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),xe(i,3),i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee;if(69===i.status){if(i.gzhead.extra){for(var n=i.pending,o=(65535&i.gzhead.extra.length)-i.gzindex;i.pending+o>i.pending_buf_size;){var a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex+=a,we(e),0!==i.pending)return i.last_flush=-1,ee;n=0,o-=a}var l=new Uint8Array(i.gzhead.extra);i.pending_buf.set(l.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending+=o,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){var u,A=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>A&&(e.adler=V(e.adler,i.pending_buf,i.pending-A,A)),we(e),0!==i.pending)return i.last_flush=-1,ee;A=0}u=i.gzindexA&&(e.adler=V(e.adler,i.pending_buf,i.pending-A,A)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){var c,h=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>h&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h)),we(e),0!==i.pending)return i.last_flush=-1,ee;h=0}c=i.gzindexh&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(we(e),0!==i.pending))return i.last_flush=-1,ee;xe(i,255&e.adler),xe(i,e.adler>>8&255),e.adler=0}if(i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee}if(0!==e.avail_in||0!==i.lookahead||t!==Y&&i.status!==ve){var d=0===i.level?Fe(i,t):i.strategy===ae?function(e,t){for(var i;;){if(0===e.lookahead&&(Ee(e),0===e.lookahead)){if(t===Y)return 1;break}if(e.match_length=0,i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2}(i,t):i.strategy===le?function(e,t){for(var i,s,r,n,o=e.window;;){if(e.lookahead<=he){if(Ee(e),e.lookahead<=he&&t===Y)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&((s=o[r=e.strstart-1])===o[++r]&&s===o[++r]&&s===o[++r])){n=e.strstart+he;do{}while(s===o[++r]&&s===o[++r]&&s===o[++r]&&s===o[++r]&&s===o[++r]&&s===o[++r]&&s===o[++r]&&s===o[++r]&&re.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2}(i,t):Se[i.level].func(i,t);if(3!==d&&4!==d||(i.status=ve),1===d||3===d)return 0===e.avail_out&&(i.last_flush=-1),ee;if(2===d&&(t===J?X(i):t!==$&&(z(i,0,0,!1),t===Z&&(_e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),we(e),0===e.avail_out))return i.last_flush=-1,ee}return t!==q?ee:i.wrap<=0?te:(2===i.wrap?(xe(i,255&e.adler),xe(i,e.adler>>8&255),xe(i,e.adler>>16&255),xe(i,e.adler>>24&255),xe(i,255&e.total_in),xe(i,e.total_in>>8&255),xe(i,e.total_in>>16&255),xe(i,e.total_in>>24&255)):(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),we(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ee:te)},He=function(e){if(Le(e))return ie;var t=e.state.status;return e.state=null,t===fe?ge(e,se):ee},je=function(e,t){var i=t.length;if(Le(e))return ie;var s=e.state,r=s.wrap;if(2===r||1===r&&s.status!==pe||s.lookahead)return ie;if(1===r&&(e.adler=N(e.adler,t,i,0)),s.wrap=0,i>=s.w_size){0===r&&(_e(s.head),s.strstart=0,s.block_start=0,s.insert=0);var n=new Uint8Array(s.w_size);n.set(t.subarray(i-s.w_size,i),0),t=n,i=s.w_size}var o=e.avail_in,a=e.next_in,l=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,Ee(s);s.lookahead>=3;){var u=s.strstart,A=s.lookahead-2;do{s.ins_h=be(s,s.ins_h,s.window[u+3-1]),s.prev[u&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=u,u++}while(--A);s.strstart=u,s.lookahead=2,Ee(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=2,s.match_available=0,e.next_in=a,e.input=l,e.avail_in=o,s.wrap=r,ee},Ge=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},ze=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=B(i))throw new TypeError(i+"must be non-object");for(var s in i)Ge(i,s)&&(e[s]=i[s])}}return e},We=function(e){for(var t=0,i=0,s=e.length;i=252?6:Ye>=248?5:Ye>=240?4:Ye>=224?3:Ye>=192?2:1;Xe[254]=Xe[254]=1;var Je=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,i,s,r,n,o=e.length,a=0;for(r=0;r>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},Ze=function(e,t){var i,s,r=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));var n=new Array(2*r);for(s=0,i=0;i4)n[s++]=65533,i+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&i1?n[s++]=65533:o<65536?n[s++]=o:(o-=65536,n[s++]=55296|o>>10&1023,n[s++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ke)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var i="",s=0;se.length&&(t=e.length);for(var i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Xe[e[i]]>t?i:t},$e=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},et=Object.prototype.toString,tt=j.Z_NO_FLUSH,it=j.Z_SYNC_FLUSH,st=j.Z_FULL_FLUSH,rt=j.Z_FINISH,nt=j.Z_OK,ot=j.Z_STREAM_END,at=j.Z_DEFAULT_COMPRESSION,lt=j.Z_DEFAULT_STRATEGY,ut=j.Z_DEFLATED;function At(e){this.options=ze({level:at,method:ut,chunkSize:16384,windowBits:15,memLevel:8,strategy:lt},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $e,this.strm.avail_out=0;var i=Ne(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==nt)throw new Error(H[i]);if(t.header&&Qe(this.strm,t.header),t.dictionary){var s;if(s="string"==typeof t.dictionary?Je(t.dictionary):"[object ArrayBuffer]"===et.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=je(this.strm,s))!==nt)throw new Error(H[i]);this._dict_set=!0}}function ct(e,t){var i=new At(t);if(i.push(e,!0),i.err)throw i.msg||H[i.err];return i.result}At.prototype.push=function(e,t){var i,s,r=this.strm,n=this.options.chunkSize;if(this.ended)return!1;for(s=t===~~t?t:!0===t?rt:tt,"string"==typeof e?r.input=Je(e):"[object ArrayBuffer]"===et.call(e)?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;;)if(0===r.avail_out&&(r.output=new Uint8Array(n),r.next_out=0,r.avail_out=n),(s===it||s===st)&&r.avail_out<=6)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else{if((i=Ve(r,s))===ot)return r.next_out>0&&this.onData(r.output.subarray(0,r.next_out)),i=He(this.strm),this.onEnd(i),this.ended=!0,i===nt;if(0!==r.avail_out){if(s>0&&r.next_out>0)this.onData(r.output.subarray(0,r.next_out)),r.avail_out=0;else if(0===r.avail_in)break}else this.onData(r.output)}return!0},At.prototype.onData=function(e){this.chunks.push(e)},At.prototype.onEnd=function(e){e===nt&&(this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ht=At,dt=ct,pt=function(e,t){return(t=t||{}).raw=!0,ct(e,t)},ft=function(e,t){return(t=t||{}).gzip=!0,ct(e,t)},vt=16209,gt=function(e,t){var i,s,r,n,o,a,l,u,A,c,h,d,p,f,v,g,m,_,y,b,w,B,x,P,C=e.state;i=e.next_in,x=e.input,s=i+(e.avail_in-5),r=e.next_out,P=e.output,n=r-(t-e.avail_out),o=r+(e.avail_out-257),a=C.dmax,l=C.wsize,u=C.whave,A=C.wnext,c=C.window,h=C.hold,d=C.bits,p=C.lencode,f=C.distcode,v=(1<>>=_=m>>>24,d-=_,0===(_=m>>>16&255))P[r++]=65535&m;else{if(!(16&_)){if(0==(64&_)){m=p[(65535&m)+(h&(1<<_)-1)];continue t}if(32&_){C.mode=16191;break e}e.msg="invalid literal/length code",C.mode=vt;break e}y=65535&m,(_&=15)&&(d<_&&(h+=x[i++]<>>=_,d-=_),d<15&&(h+=x[i++]<>>=_=m>>>24,d-=_,!(16&(_=m>>>16&255))){if(0==(64&_)){m=f[(65535&m)+(h&(1<<_)-1)];continue i}e.msg="invalid distance code",C.mode=vt;break e}if(b=65535&m,d<(_&=15)&&(h+=x[i++]<a){e.msg="invalid distance too far back",C.mode=vt;break e}if(h>>>=_,d-=_,b>(_=r-n)){if((_=b-_)>u&&C.sane){e.msg="invalid distance too far back",C.mode=vt;break e}if(w=0,B=c,0===A){if(w+=l-_,_2;)P[r++]=B[w++],P[r++]=B[w++],P[r++]=B[w++],y-=3;y&&(P[r++]=B[w++],y>1&&(P[r++]=B[w++]))}else{w=r-b;do{P[r++]=P[w++],P[r++]=P[w++],P[r++]=P[w++],y-=3}while(y>2);y&&(P[r++]=P[w++],y>1&&(P[r++]=P[w++]))}break}}break}}while(i>3,h&=(1<<(d-=y<<3))-1,e.next_in=i,e.next_out=r,e.avail_in=i=1&&0===F[b];b--);if(w>b&&(w=b),0===b)return r[n++]=20971520,r[n++]=20971520,a.bits=1,0;for(y=1;y0&&(0===e||1!==b))return-1;for(k[1]=0,m=1;m<15;m++)k[m+1]=k[m]+F[m];for(_=0;_852||2===e&&C>592)return 1;for(;;){p=m-x,o[_]+1=d?(f=I[o[_]-d],v=E[o[_]-d]):(f=96,v=0),l=1<>x)+(u-=l)]=p<<24|f<<16|v|0}while(0!==u);for(l=1<>=1;if(0!==l?(M&=l-1,M+=l):M=0,_++,0==--F[m]){if(m===b)break;m=t[i+o[_]]}if(m>w&&(M&c)!==A){for(0===x&&(x=w),h+=y,P=1<<(B=m-x);B+x852||2===e&&C>592)return 1;r[A=M&c]=w<<24|B<<16|h-n|0}}return 0!==M&&(r[h+M]=m-x<<24|64<<16|0),a.bits=w,0},Bt=j.Z_FINISH,xt=j.Z_BLOCK,Pt=j.Z_TREES,Ct=j.Z_OK,Mt=j.Z_STREAM_END,Et=j.Z_NEED_DICT,Ft=j.Z_STREAM_ERROR,kt=j.Z_DATA_ERROR,It=j.Z_MEM_ERROR,Dt=j.Z_BUF_ERROR,St=j.Z_DEFLATED,Tt=16180,Lt=16190,Rt=16191,Ut=16192,Ot=16194,Nt=16199,Qt=16200,Vt=16206,Ht=16209,jt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function Gt(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var zt,Wt,Kt=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Xt=function(e){if(Kt(e))return Ft;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Tt,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ct},Yt=function(e){if(Kt(e))return Ft;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Xt(e)},Jt=function(e,t){var i;if(Kt(e))return Ft;var s=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ft:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,Yt(e))},Zt=function(e,t){if(!e)return Ft;var i=new Gt;e.state=i,i.strm=e,i.window=null,i.mode=Tt;var s=Jt(e,t);return s!==Ct&&(e.state=null),s},qt=!0,$t=function(e){if(qt){zt=new Int32Array(512),Wt=new Int32Array(32);for(var t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(wt(1,e.lens,0,288,zt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;wt(2,e.lens,0,32,Wt,0,e.work,{bits:5}),qt=!1}e.lencode=zt,e.lenbits=9,e.distcode=Wt,e.distbits=5},ei=function(e,t,i,s){var r,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(n.window.set(t.subarray(i-n.wsize,i),0),n.wnext=0,n.whave=n.wsize):((r=n.wsize-n.wnext)>s&&(r=s),n.window.set(t.subarray(i-s,i-s+r),n.wnext),(s-=r)?(n.window.set(t.subarray(i-s,i),0),n.wnext=s,n.whave=n.wsize):(n.wnext+=r,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=V(i.check,M,2,0),u=0,A=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",i.mode=Ht;break}if((15&u)!==St){e.msg="unknown compression method",i.mode=Ht;break}if(A-=4,w=8+(15&(u>>>=4)),0===i.wbits&&(i.wbits=w),w>15||w>i.wbits){e.msg="invalid window size",i.mode=Ht;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0,i.mode=16182;case 16182:for(;A<32;){if(0===a)break e;a--,u+=s[n++]<>>8&255,M[2]=u>>>16&255,M[3]=u>>>24&255,i.check=V(i.check,M,4,0)),u=0,A=0,i.mode=16183;case 16183:for(;A<16;){if(0===a)break e;a--,u+=s[n++]<>8),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0,i.mode=16184;case 16184:if(1024&i.flags){for(;A<16;){if(0===a)break e;a--,u+=s[n++]<>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&((d=i.length)>a&&(d=a),d&&(i.head&&(w=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(s.subarray(n,n+d),w)),512&i.flags&&4&i.wrap&&(i.check=V(i.check,s,d,n)),a-=d,n+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{w=s[n+d++],i.head&&w&&i.length<65536&&(i.head.name+=String.fromCharCode(w))}while(w&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Rt;break;case 16189:for(;A<32;){if(0===a)break e;a--,u+=s[n++]<>>=7&A,A-=7&A,i.mode=Vt;break}for(;A<3;){if(0===a)break e;a--,u+=s[n++]<>>=1)){case 0:i.mode=16193;break;case 1:if($t(i),i.mode=Nt,t===Pt){u>>>=2,A-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Ht}u>>>=2,A-=2;break;case 16193:for(u>>>=7&A,A-=7&A;A<32;){if(0===a)break e;a--,u+=s[n++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Ht;break}if(i.length=65535&u,u=0,A=0,i.mode=Ot,t===Pt)break e;case Ot:i.mode=16195;case 16195:if(d=i.length){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;r.set(s.subarray(n,n+d),o),a-=d,n+=d,l-=d,o+=d,i.length-=d;break}i.mode=Rt;break;case 16196:for(;A<14;){if(0===a)break e;a--,u+=s[n++]<>>=5,A-=5,i.ndist=1+(31&u),u>>>=5,A-=5,i.ncode=4+(15&u),u>>>=4,A-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Ht;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,A-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,x={bits:i.lenbits},B=wt(0,i.lens,0,19,i.lencode,0,i.work,x),i.lenbits=x.bits,B){e.msg="invalid code lengths set",i.mode=Ht;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=s[n++]<>>=v,A-=v,i.lens[i.have++]=m;else{if(16===m){for(P=v+2;A>>=v,A-=v,0===i.have){e.msg="invalid bit length repeat",i.mode=Ht;break}w=i.lens[i.have-1],d=3+(3&u),u>>>=2,A-=2}else if(17===m){for(P=v+3;A>>=v)),u>>>=3,A-=3}else{for(P=v+7;A>>=v)),u>>>=7,A-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Ht;break}for(;d--;)i.lens[i.have++]=w}}if(i.mode===Ht)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Ht;break}if(i.lenbits=9,x={bits:i.lenbits},B=wt(1,i.lens,0,i.nlen,i.lencode,0,i.work,x),i.lenbits=x.bits,B){e.msg="invalid literal/lengths set",i.mode=Ht;break}if(i.distbits=6,i.distcode=i.distdyn,x={bits:i.distbits},B=wt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,x),i.distbits=x.bits,B){e.msg="invalid distances set",i.mode=Ht;break}if(i.mode=Nt,t===Pt)break e;case Nt:i.mode=Qt;case Qt:if(a>=6&&l>=258){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,i.hold=u,i.bits=A,gt(e,h),o=e.next_out,r=e.output,l=e.avail_out,n=e.next_in,s=e.input,a=e.avail_in,u=i.hold,A=i.bits,i.mode===Rt&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=s[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=A);){if(0===a)break e;a--,u+=s[n++]<>>=_,A-=_,i.back+=_}if(u>>>=v,A-=v,i.back+=v,i.length=m,0===g){i.mode=16205;break}if(32&g){i.back=-1,i.mode=Rt;break}if(64&g){e.msg="invalid literal/length code",i.mode=Ht;break}i.extra=15&g,i.mode=16201;case 16201:if(i.extra){for(P=i.extra;A>>=i.extra,A-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;g=(C=i.distcode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=s[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=A);){if(0===a)break e;a--,u+=s[n++]<>>=_,A-=_,i.back+=_}if(u>>>=v,A-=v,i.back+=v,64&g){e.msg="invalid distance code",i.mode=Ht;break}i.offset=m,i.extra=15&g,i.mode=16203;case 16203:if(i.extra){for(P=i.extra;A>>=i.extra,A-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Ht;break}i.mode=16204;case 16204:if(0===l)break e;if(d=h-l,i.offset>d){if((d=i.offset-d)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Ht;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=r,p=o-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{r[o++]=f[p++]}while(--d);0===i.length&&(i.mode=Qt);break;case 16205:if(0===l)break e;r[o++]=i.length,l--,i.mode=Qt;break;case Vt:if(i.wrap){for(;A<32;){if(0===a)break e;a--,u|=s[n++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $e,this.strm.avail_out=0;var i=ii(this.strm,t.windowBits);if(i!==ci)throw new Error(H[i]);if(this.header=new ai,ni(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Je(t.dictionary):"[object ArrayBuffer]"===li.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=oi(this.strm,t.dictionary))!==ci))throw new Error(H[i])}function mi(e,t){var i=new gi(t);if(i.push(e),i.err)throw i.msg||H[i.err];return i.result}gi.prototype.push=function(e,t){var i,s,r,n=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(s=t===~~t?t:!0===t?Ai:ui,"[object ArrayBuffer]"===li.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(o),n.next_out=0,n.avail_out=o),(i=si(n,s))===di&&a&&((i=oi(n,a))===ci?i=si(n,s):i===fi&&(i=di));n.avail_in>0&&i===hi&&n.state.wrap>0&&0!==e[n.next_in];)ti(n),i=si(n,s);switch(i){case pi:case fi:case di:case vi:return this.onEnd(i),this.ended=!0,!1}if(r=n.avail_out,n.next_out&&(0===n.avail_out||i===hi))if("string"===this.options.to){var l=qe(n.output,n.next_out),u=n.next_out-l,A=Ze(n.output,l);n.next_out=u,n.avail_out=o-u,u&&n.output.set(n.output.subarray(l,l+u),0),this.onData(A)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(i!==ci||0!==r){if(i===hi)return i=ri(this.strm),this.onEnd(i),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},gi.prototype.onData=function(e){this.chunks.push(e)},gi.prototype.onEnd=function(e){e===ci&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var _i=function(e,t){return(t=t||{}).raw=!0,mi(e,t)},yi=ht,bi=dt,wi=pt,Bi=ft,xi=gi,Pi=mi,Ci=_i,Mi=mi,Ei=j,Fi={Deflate:yi,deflate:bi,deflateRaw:wi,gzip:Bi,Inflate:xi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=yi,e.Inflate=xi,e.constants=Ei,e.default=Fi,e.deflate=bi,e.deflateRaw=wi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var pF=Object.freeze({__proto__:null}),fF=window.pako||pF;fF.inflate||(fF=fF.default);var vF,gF=(vF=new Float32Array(3),function(e){return vF[0]=e[0]/255,vF[1]=e[1]/255,vF[2]=e[2]/255,vF});var mF={version:1,parse:function(e,t,i,s,r,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}(i),a=function(e){return{positions:new Uint16Array(fF.inflate(e.positions).buffer),normals:new Int8Array(fF.inflate(e.normals).buffer),indices:new Uint32Array(fF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(fF.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(fF.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(fF.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(fF.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(fF.inflate(e.meshColors).buffer),entityIDs:fF.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(fF.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(fF.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(fF.inflate(e.positionsDecodeMatrix).buffer)}}(o);!function(e,t,i,s,r,n){n.getNextId(),s.positionsCompression="precompressed",s.normalsCompression="precompressed";for(var o=i.positions,a=i.normals,l=i.indices,u=i.edgeIndices,A=i.meshPositions,c=i.meshIndices,h=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),f=i.entityMeshes,v=i.entityIsObjects,g=A.length,m=f.length,_=0;_v[t]?1:0}));for(var E=0;E1||(F[R]=k)}for(var U=0;U1,V=CF(g.subarray(4*O,4*O+3)),H=g[4*O+3]/255,j=a.subarray(d[O],N?a.length:d[O+1]),G=l.subarray(d[O],N?l.length:d[O+1]),z=u.subarray(p[O],N?u.length:p[O+1]),W=A.subarray(f[O],N?A.length:f[O+1]),K=c.subarray(v[O],v[O]+16);if(Q){var X="".concat(o,"-geometry.").concat(O);s.createGeometry({id:X,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K})}else{var Y="".concat(o,"-").concat(O);_[F[O]],s.createMesh(le.apply({},{id:Y,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K,color:V,opacity:H}))}}for(var J=0,Z=0;Z1){var oe="".concat(o,"-instance.").concat(J++),ae="".concat(o,"-geometry.").concat(ne),ue=16*b[Z],Ae=h.subarray(ue,ue+16);s.createMesh(le.apply({},{id:oe,geometryId:ae,matrix:Ae})),se.push(oe)}else se.push(ne)}se.length>0&&s.createEntity(le.apply({},{id:ee,isObject:!0,meshIds:se}))}}(0,0,a,s,0,n)}},EF=window.pako||pF;EF.inflate||(EF=EF.default);var FF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var kF={version:5,parse:function(e,t,i,s,r,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}(i),a=function(e){return{positions:new Float32Array(EF.inflate(e.positions).buffer),normals:new Int8Array(EF.inflate(e.normals).buffer),indices:new Uint32Array(EF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(EF.inflate(e.edgeIndices).buffer),matrices:new Float32Array(EF.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(EF.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(EF.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(EF.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(EF.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(EF.inflate(e.primitiveInstances).buffer),eachEntityId:EF.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(EF.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(EF.inflate(e.eachEntityMatricesPortion).buffer)}}(o);!function(e,t,i,s,r,n){var o=n.getNextId();s.positionsCompression="disabled",s.normalsCompression="precompressed";for(var a=i.positions,l=i.normals,u=i.indices,A=i.edgeIndices,c=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,v=i.primitiveInstances,g=JSON.parse(i.eachEntityId),m=i.eachEntityPrimitiveInstancesPortion,_=i.eachEntityMatricesPortion,y=h.length,b=v.length,w=new Uint8Array(y),B=g.length,x=0;x1||(P[D]=C)}for(var S=0;S1,R=FF(f.subarray(4*S,4*S+3)),U=f[4*S+3]/255,O=a.subarray(h[S],T?a.length:h[S+1]),N=l.subarray(h[S],T?l.length:h[S+1]),Q=u.subarray(d[S],T?u.length:d[S+1]),V=A.subarray(p[S],T?A.length:p[S+1]);if(L){var H="".concat(o,"-geometry.").concat(S);s.createGeometry({id:H,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V})}else{var j=S;g[P[S]],s.createMesh(le.apply({},{id:j,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V,color:R,opacity:U}))}}for(var G=0,z=0;z1){var ee="instance."+G++,te="geometry"+$,ie=16*_[z],se=c.subarray(ie,ie+16);s.createMesh(le.apply({},{id:ee,geometryId:te,matrix:se})),Z.push(ee)}else Z.push($)}Z.length>0&&s.createEntity(le.apply({},{id:X,isObject:!0,meshIds:Z}))}}(0,0,a,s,0,n)}},IF=window.pako||pF;IF.inflate||(IF=IF.default);var DF,SF=(DF=new Float32Array(3),function(e){return DF[0]=e[0]/255,DF[1]=e[1]/255,DF[2]=e[2]/255,DF});var TF={version:6,parse:function(e,t,i,s,r,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:IF.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:IF.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,s,r,n){for(var o=n.getNextId(),a=i.positions,l=i.normals,u=i.indices,A=i.edgeIndices,c=i.matrices,h=i.reusedPrimitivesDecodeMatrix,d=i.eachPrimitivePositionsAndNormalsPortion,p=i.eachPrimitiveIndicesPortion,f=i.eachPrimitiveEdgeIndicesPortion,v=i.eachPrimitiveColorAndOpacity,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,y=i.eachEntityMatricesPortion,b=i.eachTileAABB,w=i.eachTileEntitiesPortion,B=d.length,x=g.length,P=m.length,C=w.length,M=new Uint32Array(B),E=0;E1,se=te===B-1,re=a.subarray(d[te],se?a.length:d[te+1]),ne=l.subarray(d[te],se?l.length:d[te+1]),oe=u.subarray(p[te],se?u.length:p[te+1]),ae=A.subarray(f[te],se?A.length:f[te+1]),ue=SF(v.subarray(4*te,4*te+3)),Ae=v[4*te+3]/255,ce=n.getNextId();if(ie){var he="".concat(o,"-geometry.").concat(D,".").concat(te);N[he]||(s.createGeometry({id:he,primitive:"triangles",positionsCompressed:re,indices:oe,edgeIndices:ae,positionsDecodeMatrix:h}),N[he]=!0),s.createMesh(le.apply(Z,{id:ce,geometryId:he,origin:k,matrix:G,color:ue,opacity:Ae})),X.push(ce)}else s.createMesh(le.apply(Z,{id:ce,origin:k,primitive:"triangles",positionsCompressed:re,normalsCompressed:ne,indices:oe,edgeIndices:ae,positionsDecodeMatrix:O,color:ue,opacity:Ae})),X.push(ce)}X.length>0&&s.createEntity(le.apply(J,{id:H,isObject:!0,meshIds:X}))}}}(e,t,a,s,0,n)}},LF=window.pako||pF;LF.inflate||(LF=LF.default);var RF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function UF(e){for(var t=[],i=0,s=e.length;i1,ne=se===M-1,oe=RF(w.subarray(6*ie,6*ie+3)),ae=w[6*ie+3]/255,ue=w[6*ie+4]/255,Ae=w[6*ie+5]/255,ce=n.getNextId();if(re){var he=b[ie],de=h.slice(he,he+16),pe="".concat(o,"-geometry.").concat(R,".").concat(se);if(!j[pe]){var fe=void 0,ve=void 0,ge=void 0,me=void 0,_e=void 0,ye=void 0;switch(p[se]){case 0:fe="solid",ve=a.subarray(f[se],ne?a.length:f[se+1]),ge=l.subarray(v[se],ne?l.length:v[se+1]),_e=A.subarray(m[se],ne?A.length:m[se+1]),ye=c.subarray(_[se],ne?c.length:_[se+1]);break;case 1:fe="surface",ve=a.subarray(f[se],ne?a.length:f[se+1]),ge=l.subarray(v[se],ne?l.length:v[se+1]),_e=A.subarray(m[se],ne?A.length:m[se+1]),ye=c.subarray(_[se],ne?c.length:_[se+1]);break;case 2:fe="points",ve=a.subarray(f[se],ne?a.length:f[se+1]),me=UF(u.subarray(g[se],ne?u.length:g[se+1]));break;case 3:fe="lines",ve=a.subarray(f[se],ne?a.length:f[se+1]),_e=A.subarray(m[se],ne?A.length:m[se+1]);break;default:continue}s.createGeometry({id:pe,primitive:fe,positionsCompressed:ve,normalsCompressed:ge,colors:me,indices:_e,edgeIndices:ye,positionsDecodeMatrix:d}),j[pe]=!0}s.createMesh(le.apply(ee,{id:ce,geometryId:pe,origin:T,matrix:de,color:oe,metallic:ue,roughness:Ae,opacity:ae})),J.push(ce)}else{var be=void 0,we=void 0,Be=void 0,xe=void 0,Pe=void 0,Ce=void 0;switch(p[se]){case 0:be="solid",we=a.subarray(f[se],ne?a.length:f[se+1]),Be=l.subarray(v[se],ne?l.length:v[se+1]),Pe=A.subarray(m[se],ne?A.length:m[se+1]),Ce=c.subarray(_[se],ne?c.length:_[se+1]);break;case 1:be="surface",we=a.subarray(f[se],ne?a.length:f[se+1]),Be=l.subarray(v[se],ne?l.length:v[se+1]),Pe=A.subarray(m[se],ne?A.length:m[se+1]),Ce=c.subarray(_[se],ne?c.length:_[se+1]);break;case 2:be="points",we=a.subarray(f[se],ne?a.length:f[se+1]),xe=UF(u.subarray(g[se],ne?u.length:g[se+1]));break;case 3:be="lines",we=a.subarray(f[se],ne?a.length:f[se+1]),Pe=A.subarray(m[se],ne?A.length:m[se+1]);break;default:continue}s.createMesh(le.apply(ee,{id:ce,origin:T,primitive:be,positionsCompressed:we,normalsCompressed:Be,colors:xe,indices:Pe,edgeIndices:Ce,positionsDecodeMatrix:H,color:oe,metallic:ue,roughness:Ae,opacity:ae})),J.push(ce)}}J.length>0&&s.createEntity(le.apply(q,{id:W,isObject:!0,meshIds:J}))}}}(e,t,a,s,0,n)}},NF=window.pako||pF;NF.inflate||(NF=NF.default);var QF=$.vec4(),VF=$.vec4();var HF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function jF(e){for(var t=[],i=0,s=e.length;i1,ye=me===S-1,be=HF(M.subarray(6*ge,6*ge+3)),we=M[6*ge+3]/255,Be=M[6*ge+4]/255,xe=M[6*ge+5]/255,Pe=n.getNextId();if(_e){var Ce=C[ge],Me=g.slice(Ce,Ce+16),Ee="".concat(o,"-geometry.").concat(J,".").concat(me),Fe=Y[Ee];if(!Fe){Fe={batchThisMesh:!t.reuseGeometries};var ke=!1;switch(_[me]){case 0:Fe.primitiveName="solid",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),Fe.geometryEdgeIndices=v.subarray(x[me],ye?v.length:x[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 1:Fe.primitiveName="surface",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),Fe.geometryEdgeIndices=v.subarray(x[me],ye?v.length:x[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 2:Fe.primitiveName="points",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryColors=jF(p.subarray(w[me],ye?p.length:w[me+1])),ke=Fe.geometryPositions.length>0;break;case 3:Fe.primitiveName="lines",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;default:continue}if(ke||(Fe=null),Fe&&(Fe.geometryPositions.length,Fe.batchThisMesh)){Fe.decompressedPositions=new Float32Array(Fe.geometryPositions.length);for(var Ie=Fe.geometryPositions,De=Fe.decompressedPositions,Se=0,Te=Ie.length;Se0&&je.length>0;break;case 1:Ne="surface",Qe=h.subarray(y[me],ye?h.length:y[me+1]),Ve=d.subarray(b[me],ye?d.length:b[me+1]),je=f.subarray(B[me],ye?f.length:B[me+1]),Ge=v.subarray(x[me],ye?v.length:x[me+1]),ze=Qe.length>0&&je.length>0;break;case 2:Ne="points",Qe=h.subarray(y[me],ye?h.length:y[me+1]),He=jF(p.subarray(w[me],ye?p.length:w[me+1])),ze=Qe.length>0;break;case 3:Ne="lines",Qe=h.subarray(y[me],ye?h.length:y[me+1]),je=f.subarray(B[me],ye?f.length:B[me+1]),ze=Qe.length>0&&je.length>0;break;default:continue}ze&&(s.createMesh(le.apply(fe,{id:Pe,origin:K,primitive:Ne,positionsCompressed:Qe,normalsCompressed:Ve,colorsCompressed:He,indices:je,edgeIndices:Ge,positionsDecodeMatrix:se,color:be,metallic:Be,roughness:xe,opacity:we})),he.push(Pe))}}he.length>0&&s.createEntity(le.apply(pe,{id:ae,isObject:!0,meshIds:he}))}}}(e,t,a,s,r,n)}},zF=window.pako||pF;zF.inflate||(zF=zF.default);var WF=$.vec4(),KF=$.vec4();var XF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var YF={version:9,parse:function(e,t,i,s,r,n){var o=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:zF.inflate(e,t).buffer}return{metadata:JSON.parse(zF.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(zF.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,s,r,n){var o=n.getNextId(),a=i.metadata,l=i.positions,u=i.normals,A=i.colors,c=i.indices,h=i.edgeIndices,d=i.matrices,p=i.reusedGeometriesDecodeMatrix,f=i.eachGeometryPrimitiveType,v=i.eachGeometryPositionsPortion,g=i.eachGeometryNormalsPortion,m=i.eachGeometryColorsPortion,_=i.eachGeometryIndicesPortion,y=i.eachGeometryEdgeIndicesPortion,b=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,B=i.eachMeshMaterial,x=i.eachEntityId,P=i.eachEntityMeshesPortion,C=i.eachTileAABB,M=i.eachTileEntitiesPortion,E=v.length,F=b.length,k=P.length,I=M.length;r&&r.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(var D=new Uint32Array(E),S=0;S1,ae=ne===E-1,ue=XF(B.subarray(6*re,6*re+3)),Ae=B[6*re+3]/255,ce=B[6*re+4]/255,he=B[6*re+5]/255,de=n.getNextId();if(oe){var pe=w[re],fe=d.slice(pe,pe+16),ve="".concat(o,"-geometry.").concat(O,".").concat(ne),ge=U[ve];if(!ge){ge={batchThisMesh:!t.reuseGeometries};var me=!1;switch(f[ne]){case 0:ge.primitiveName="solid",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 1:ge.primitiveName="surface",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 2:ge.primitiveName="points",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryColors=A.subarray(m[ne],ae?A.length:m[ne+1]),me=ge.geometryPositions.length>0;break;case 3:ge.primitiveName="lines",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;default:continue}if(me||(ge=null),ge&&(ge.geometryPositions.length,ge.batchThisMesh)){ge.decompressedPositions=new Float32Array(ge.geometryPositions.length),ge.transformedAndRecompressedPositions=new Uint16Array(ge.geometryPositions.length);for(var _e=ge.geometryPositions,ye=ge.decompressedPositions,be=0,we=_e.length;be0&&Ie.length>0;break;case 1:Me="surface",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Fe=u.subarray(g[ne],ae?u.length:g[ne+1]),Ie=c.subarray(_[ne],ae?c.length:_[ne+1]),De=h.subarray(y[ne],ae?h.length:y[ne+1]),Se=Ee.length>0&&Ie.length>0;break;case 2:Me="points",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),ke=A.subarray(m[ne],ae?A.length:m[ne+1]),Se=Ee.length>0;break;case 3:Me="lines",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Ie=c.subarray(_[ne],ae?c.length:_[ne+1]),Se=Ee.length>0&&Ie.length>0;break;default:continue}Se&&(s.createMesh(le.apply(ie,{id:de,origin:L,primitive:Me,positionsCompressed:Ee,normalsCompressed:Fe,colorsCompressed:ke,indices:Ie,edgeIndices:De,positionsDecodeMatrix:G,color:ue,metallic:ce,roughness:he,opacity:Ae})),q.push(de))}}q.length>0&&s.createEntity(le.apply(te,{id:X,isObject:!0,meshIds:q}))}}}(e,t,a,s,r,n)}},JF=window.pako||pF;JF.inflate||(JF=JF.default);var ZF=$.vec4(),qF=$.vec4();var $F=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function ek(e,t){var i=[];if(t.length>1)for(var s=0,r=t.length-1;s1)for(var n=0,o=e.length/3-1;n0,W=9*V,K=1===A[W+0],X=A[W+1];A[W+2],A[W+3];var Y=A[W+4],J=A[W+5],Z=A[W+6],q=A[W+7],ee=A[W+8];if(z){var te=new Uint8Array(l.subarray(j,G)).buffer,ie="".concat(o,"-texture-").concat(V);if(K)s.createTexture({id:ie,buffers:[te],minFilter:Y,magFilter:J,wrapS:Z,wrapT:q,wrapR:ee});else{var se=new Blob([te],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),re=(window.URL||window.webkitURL).createObjectURL(se),ne=document.createElement("img");ne.src=re,s.createTexture({id:ie,image:ne,minFilter:Y,magFilter:J,wrapS:Z,wrapT:q,wrapR:ee})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(Ae):null,normalsTextureId:he>=0?"".concat(o,"-texture-").concat(he):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=$F(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Ye=k[6*Qe+5]/255,Je=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryNormals=h.subarray(w[Ve],je?h.length:w[Ve+1]),et.geometryUVs=p.subarray(x[Ve],je?p.length:x[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryNormals=h.subarray(w[Ve],je?h.length:w[Ve+1]),et.geometryUVs=p.subarray(x[Ve],je?p.length:x[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryColors=d.subarray(B[Ve],je?d.length:B[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryIndices=ek(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,st=et.decompressedPositions,rt=0,nt=it.length;rt0&&ft.length>0;break;case 1:At="surface",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),ht=h.subarray(w[Ve],je?h.length:w[Ve+1]),dt=p.subarray(x[Ve],je?p.length:x[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=ct.length>0&&ft.length>0;break;case 2:At="points",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),pt=d.subarray(B[Ve],je?d.length:B[Ve+1]),gt=ct.length>0;break;case 3:At="lines",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=ct.length>0&&ft.length>0;break;case 4:At="lines",ft=ek(ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=ct.length>0&&ft.length>0;break;default:continue}gt&&(s.createMesh(le.apply(Oe,{id:Je,textureSetId:ze,origin:me,primitive:At,positionsCompressed:ct,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Ye,opacity:Ke})),Le.push(Je))}}Le.length>0&&s.createEntity(le.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,a,s,r,n)}},ik={};ik[mF.version]=mF,ik[bF.version]=bF,ik[xF.version]=xF,ik[MF.version]=MF,ik[kF.version]=kF,ik[TF.version]=TF,ik[OF.version]=OF,ik[GF.version]=GF,ik[YF.version]=YF,ik[tk.version]=tk;var sk=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"XKTLoader",e,r))._maxGeometryBatchSize=r.maxGeometryBatchSize,s.textureTranscoder=r.textureTranscoder,s.dataSource=r.dataSource,s.objectDefaults=r.objectDefaults,s.includeTypes=r.includeTypes,s.excludeTypes=r.excludeTypes,s.excludeUnclassifiedObjects=r.excludeUnclassifiedObjects,s.reuseGeometries=r.reuseGeometries,s}return C(i,[{key:"supportedVersions",get:function(){return Object.keys(ik)}},{key:"textureTranscoder",get:function(){return this._textureTranscoder},set:function(e){this._textureTranscoder=e}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new dF}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"reuseGeometries",get:function(){return this._reuseGeometries},set:function(e){this._reuseGeometries=!1!==e}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id),!(t.src||t.xkt||t.manifestSrc||t.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),A;var i={},s=t.includeTypes||this._includeTypes,r=t.excludeTypes||this._excludeTypes,n=t.objectDefaults||this._objectDefaults;if(i.reuseGeometries=null!==t.reuseGeometries&&void 0!==t.reuseGeometries?t.reuseGeometries:!1!==this._reuseGeometries,s){i.includeTypesMap={};for(var o=0,a=s.length;o=t.length?n():e._dataSource.getMetaModel("".concat(m).concat(t[a]),(function(t){h.loadData(t,{includeTypes:s,excludeTypes:r,globalizeObjectIds:i.globalizeObjectIds}),a++,e.scheduleTask(l,100)}),o)}()},y=function(s,r,n){var o=0;!function a(){o>=s.length?r():e._dataSource.getXKT("".concat(m).concat(s[o]),(function(s){e._parseModel(s,t,i,A,null,v),o++,e.scheduleTask(a,100)}),n)}()},b=function(s,r,n){var o=0;!function a(){o>=s.length?r():e._dataSource.getXKT("".concat(m).concat(s[o]),(function(s){e._parseModel(s,t,i,A,h,v),o++,e.scheduleTask(a,100)}),n)}()};if(t.manifest){var w=t.manifest,B=w.xktFiles;if(!B||0===B.length)return void p("load(): Failed to load model manifest - manifest not valid");var x=w.metaModelFiles;x?_(x,(function(){y(B,d,p)}),p):b(B,d,p)}else this._dataSource.getManifest(t.manifestSrc,(function(e){if(!A.destroyed){var t=e.xktFiles;if(t&&0!==t.length){var i=e.metaModelFiles;i?_(i,(function(){y(t,d,p)}),p):b(t,d,p)}else p("load(): Failed to load model manifest - manifest not valid")}}),p)}return A}},{key:"_loadModel",value:function(e,t,i,s,r,n,o,a){var l=this;this._dataSource.getXKT(t.src,(function(e){l._parseModel(e,t,i,s,r,n),o()}),a)}},{key:"_parseModel",value:function(e,t,i,s,r,n){if(!s.destroyed){var o=new DataView(e),a=new Uint8Array(e),l=o.getUint32(0,!0),u=ik[l];if(u){this.log("Loading .xkt V"+l);for(var A=o.getUint32(4,!0),c=[],h=4*(A+2),d=0;de.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function p(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:o}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:o}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function v(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var n,o=r.length,a=r;for(r="",n=0;n<3*Math.floor((o+t.length)/3)-o;n++)a+=String.fromCharCode(t[n]);for(;n2?s+=e.btoa(a):r=a,i()},i.getData=function(t){t(s+e.btoa(r))}}function g(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function m(e,t,i,s,r,o,a,l,u,A){var c,h,d,p=0,f=t.sn;function v(){e.removeEventListener("message",g,!1),l(h,d)}function g(t){var i=t.data,r=i.data,n=i.error;if(n)return n.toString=function(){return"Error: "+this.message},void u(n);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(h+=r.length,s.writeUint8Array(r,(function(){m()}),A)):m();break;case"flush":d=i.crc,r?(h+=r.length,s.writeUint8Array(r,(function(){v()}),A)):v();break;case"progress":a&&a(c+i.loaded,o);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function m(){(c=p*n)<=o?i.readUint8Array(r+c,Math.min(n,o-c),(function(i){a&&a(c,o);var s=0===c?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}p++}),u):e.postMessage({sn:f,type:"flush"})}h=0,e.addEventListener("message",g,!1),m()}function _(e,t,i,s,r,o,l,u,A,c){var h,d=0,p=0,f="input"===o,v="output"===o,g=new a;!function o(){var a;if((h=d*n)127?r[i-128]:String.fromCharCode(i);return s}function w(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function P(t,n,o){var a=0;function l(){}l.prototype.getData=function(s,n,l,A){var c=this;function h(e,t){A&&!function(e){var t=u(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?o("CRC failed."):s.getData((function(e){n(e)}))}function d(e){o(e||r)}function p(e){o(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(r){var n,f=u(r.length,r);1347093252==f.view.getUint32(0)?(x(c,f,4,!1,o),n=c.offset+30+c.filenameLength+c.extraFieldLength,s.init((function(){0===c.compressionMethod?y(c._worker,a++,t,s,n,c.compressedSize,A,h,l,d,p):function(t,i,s,r,n,o,a,l,u,A,c){var h=a?"output":"none";e.zip.useWebWorkers?m(t,{sn:i,codecClass:"Inflater",crcType:h},s,r,n,o,u,l,A,c):_(new e.zip.Inflater,s,r,n,o,h,u,l,A,c)}(c._worker,a++,t,s,n,c.compressedSize,A,h,l,d,p)}),p)):o(i)}),d)};var A={getEntries:function(e){var r=this._worker;!function(e){t.size<22?o(i):r(22,(function(){r(Math.min(65558,t.size),(function(){o(i)}))}));function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){o(s)}))}}((function(n){var a,A;a=n.getUint32(16,!0),A=n.getUint16(8,!0),a<0||a>=t.size?o(i):t.readUint8Array(a,t.size-a,(function(t){var s,n,a,c,h=0,d=[],p=u(t.length,t);for(s=0;s>>8^i[255&(t^e[s])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new A,c.prototype.constructor=c,h.prototype=new A,h.prototype.constructor=h,d.prototype=new A,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,v.prototype=new p,v.prototype.constructor=v,g.prototype=new p,g.prototype.constructor=g;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function k(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));r=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(r)}else(r=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var n=new Worker(r[0]);n.codecTime=n.crcTime=0,n.postMessage({type:"importScripts",scripts:r.slice(1)}),n.addEventListener("message",(function e(t){var r=t.data;if(r.error)return n.terminate(),void s(r.error);"importScripts"===r.type&&(n.removeEventListener("message",e),n.removeEventListener("error",o),i(n))})),n.addEventListener("error",o)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function o(e){n.terminate(),s(e)}}function I(e){console.error(e)}e.zip={Reader:A,Writer:p,BlobReader:d,Data64URIReader:h,TextReader:c,BlobWriter:g,Data64URIWriter:v,TextWriter:f,createReader:function(e,t,i){i=i||I,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||I,s=!!s,e.init((function(){E(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(nk);var ok=nk.zip;!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function n(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var n=new XMLHttpRequest;n.addEventListener("load",(function(){t.size=Number(n.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),n.addEventListener("error",r,!1),n.open("HEAD",e),n.send()}else i(s,r)},t.readUint8Array=function(e,s,r,n){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),n)}}function o(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var n=new XMLHttpRequest;n.open("GET",e),n.responseType="arraybuffer",n.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),n.addEventListener("load",(function(){s(n.response)}),!1),n.addEventListener("error",r,!1),n.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function a(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function u(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,n){var o=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=n,s.write(o)},r.getData=function(t){e.file(t)}}n.prototype=new s,n.prototype.constructor=n,o.prototype=new s,o.prototype.constructor=o,a.prototype=new s,a.prototype.constructor=a,l.prototype=new r,l.prototype.constructor=l,u.prototype=new r,u.prototype.constructor=u,e.FileWriter=u,e.HttpReader=n,e.HttpRangeReader=o,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,s,r){return function(i,s,r,n){if(i.directory)return n?new t(i.fs,s,r,i):new e.fs.ZipFileEntry(i.fs,s,r,i);throw"Parent entry is not a directory."}(this,i,{data:s,Reader:r?o:n})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new o(e):new n(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(ok);var ak=["4.2"],lk=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.supportedSchemas=ak,this._xrayOpacity=.7,this._src=null,this._options=i,this.viewpoint=null,i.workerScriptsPath?(ok.workerScriptsPath=i.workerScriptsPath,this.src=i.src,this.xrayOpacity=.7,this.displayEffect=i.displayEffect,this.createMetaModel=i.createMetaModel):t.error("Config expected: workerScriptsPath")}return C(e,[{key:"load",value:function(e,t,i,s,r,n){switch(s.materialType){case"MetallicMaterial":t._defaultMaterial=new Cn(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Fn(t,{diffuse:[1,1,1],specular:$.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new Ni(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Bn(t,{color:[0,0,0],lineWidth:2});var o=t.scene.canvas.spinner;o.processes++,uk(e,t,i,s,(function(){o.processes--,r&&r(),t.fire("loaded",!0,!1)}),(function(e){o.processes--,t.error(e),n&&n(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}]),e}(),uk=function(e,t,i,s,r,n){!function(e,t,i){var s=new gk;s.load(e,(function(){t(s)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){Ak(e,i,s,t,r,n)}),n)},Ak=function(){return function(t,i,s,r,n){var o={plugin:t,zip:i,edgeThreshold:30,materialType:s.materialType,scene:r.scene,modelNode:r,info:{references:{}},materials:{}};s.createMetaModel&&(o.metaModelData={modelId:r.id,metaObjects:[{name:r.id,type:"Default",id:r.id}]}),r.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(s,r){for(var n=r.children,o=0,a=n.length;o0){for(var o=n.trim().split(" "),a=new Int16Array(o.length),l=0,u=0,A=o.length;u0){i.primitive="triangles";for(var n=[],o=0,a=r.length;o=t.length)i();else{var a=t[n].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var u=a.lastIndexOf("#");u>0&&(a=a.substring(0,u)),s[a]?r(n+1):function(e,t,i){e.zip.getFile(t,(function(t,s){!function(e,t,i){for(var s,r=t.children,n=0,o=r.length;n0)for(var s=0,r=t.length;s1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),s=t.call(this,"XML3DLoader",e,r),r.workerScriptsPath?(s._workerScriptsPath=r.workerScriptsPath,s._loader=new lk(b(s),r),s.supportedSchemas=s._loader.supportedSchemas,s):(s.error("Config expected: workerScriptsPath"),y(s))}return C(i,[{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.workerScriptsPath=this._workerScriptsPath,e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new wn(this.viewer.scene,le.apply(e,{isModel:!0})),i=e.src;return i?(this._loader.load(this,t,i,e),t):(this.error("load() param expected: src"),t)}}]),i}(),yk=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getIFC",value:function(e,t,i){e=this._cacheBusterURL(e);var s=function(){};t=t||s,i=i||s;var r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){var n=!!r[2],o=r[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,"ifcLoader",e,r)).dataSource=r.dataSource,s.objectDefaults=r.objectDefaults,s.includeTypes=r.includeTypes,s.excludeTypes=r.excludeTypes,s.excludeUnclassifiedObjects=r.excludeUnclassifiedObjects,!r.WebIFC)throw"Parameter expected: WebIFC";if(!r.IfcAPI)throw"Parameter expected: IfcAPI";return s._webIFC=r.WebIFC,s._ifcAPI=r.IfcAPI,s}return C(i,[{key:"supportedVersions",get:function(){return["2x3","4"]}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new yk}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new hh(this.viewer.scene,le.apply(e,{isModel:!0}));if(!e.src&&!e.ifc)return this.error("load() param expected: src or IFC"),t;var i={autoNormals:!0};if(!1!==e.loadMetadata){var s=e.includeTypes||this._includeTypes,r=e.excludeTypes||this._excludeTypes,n=e.objectDefaults||this._objectDefaults;if(s){i.includeTypesMap={};for(var o=0,a=s.length;o0){for(var l=n.Name.value,u=[],A=0,c=a.length;A0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getLAS",value:function(e,t,i){e=this._cacheBusterURL(e);var s=function(){};t=t||s,i=i||s;var r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){var n=!!r[2],o=r[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"lasLoader",e,r)).dataSource=r.dataSource,s.skip=r.skip,s.fp64=r.fp64,s.colorDepth=r.colorDepth,s}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new wk}},{key:"skip",get:function(){return this._skip},set:function(e){this._skip=e||1}},{key:"fp64",get:function(){return this._fp64},set:function(e){this._fp64=!!e}},{key:"colorDepth",get:function(){return this._colorDepth},set:function(e){this._colorDepth=e||"auto"}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0}));if(!t.src&&!t.las)return this.error("load() param expected: src or las"),i;var s={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(t.src)this._loadModel(t.src,t,s,i);else{var r=this.viewer.scene.canvas.spinner;r.processes++,this._parseModel(t.las,t,s,i).then((function(){r.processes--}),(function(t){r.processes--,e.error(t),i.fire("error",t)}))}return i}},{key:"_loadModel",value:function(e,t,i,s){var r=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getLAS(t.src,(function(e){r._parseModel(e,t,i,s).then((function(){n.processes--}),(function(e){n.processes--,r.error(e),s.fire("error",e)}))}),(function(e){n.processes--,r.error(e),s.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,s){var r=this;function n(e){var i=e.value;if(t.rotateX&&i)for(var s=0,r=i.length;s=e.length)return[e];for(var i=[],s=0;s0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getCityJSON",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}();function Dk(e,t,i){i=i||2;var s,r,n,o,a,l,u,A=t&&t.length,c=A?t[0]*i:e.length,h=Sk(e,0,c,i,!0),d=[];if(!h||h.next===h.prev)return d;if(A&&(h=function(e,t,i,s){var r,n,o,a=[];for(r=0,n=t.length;r80*i){s=n=e[0],r=o=e[1];for(var p=i;pn&&(n=a),l>o&&(o=l);u=0!==(u=Math.max(n-s,o-r))?1/u:0}return Lk(h,d,i,s,r,u),d}function Sk(e,t,i,s,r){var n,o;if(r===sI(e,t,i,s)>0)for(n=t;n=t;n-=s)o=eI(n,e[n],e[n+1],o);return o&&Xk(o,o.next)&&(tI(o),o=o.next),o}function Tk(e,t){if(!e)return e;t||(t=e);var i,s=e;do{if(i=!1,s.steiner||!Xk(s,s.next)&&0!==Kk(s.prev,s,s.next))s=s.next;else{if(tI(s),(s=t=s.prev)===s.next)break;i=!0}}while(i||s!==t);return t}function Lk(e,t,i,s,r,n,o){if(e){!o&&n&&function(e,t,i,s){var r=e;do{null===r.z&&(r.z=jk(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){var t,i,s,r,n,o,a,l,u=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,s=i,a=0,t=0;t0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),n?n.nextZ=r:e=r,r.prevZ=n,n=r;i=s}n.nextZ=null,u*=2}while(o>1)}(r)}(e,s,r,n);for(var a,l,u=e;e.prev!==e.next;)if(a=e.prev,l=e.next,n?Uk(e,s,r,n):Rk(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),tI(e),e=l.next,u=l.next;else if((e=l)===u){o?1===o?Lk(e=Ok(Tk(e),t,i),t,i,s,r,n,2):2===o&&Nk(e,t,i,s,r,n):Lk(Tk(e),t,i,s,r,n,1);break}}}function Rk(e){var t=e.prev,i=e,s=e.next;if(Kk(t,i,s)>=0)return!1;for(var r=e.next.next;r!==e.prev;){if(zk(t.x,t.y,i.x,i.y,s.x,s.y,r.x,r.y)&&Kk(r.prev,r,r.next)>=0)return!1;r=r.next}return!0}function Uk(e,t,i,s){var r=e.prev,n=e,o=e.next;if(Kk(r,n,o)>=0)return!1;for(var a=r.xn.x?r.x>o.x?r.x:o.x:n.x>o.x?n.x:o.x,A=r.y>n.y?r.y>o.y?r.y:o.y:n.y>o.y?n.y:o.y,c=jk(a,l,t,i,s),h=jk(u,A,t,i,s),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=h;){if(d!==e.prev&&d!==e.next&&zk(r.x,r.y,n.x,n.y,o.x,o.y,d.x,d.y)&&Kk(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&zk(r.x,r.y,n.x,n.y,o.x,o.y,p.x,p.y)&&Kk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&zk(r.x,r.y,n.x,n.y,o.x,o.y,d.x,d.y)&&Kk(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==e.prev&&p!==e.next&&zk(r.x,r.y,n.x,n.y,o.x,o.y,p.x,p.y)&&Kk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function Ok(e,t,i){var s=e;do{var r=s.prev,n=s.next.next;!Xk(r,n)&&Yk(r,s,s.next,n)&&qk(r,n)&&qk(n,r)&&(t.push(r.i/i),t.push(s.i/i),t.push(n.i/i),tI(s),tI(s.next),s=e=n),s=s.next}while(s!==e);return Tk(s)}function Nk(e,t,i,s,r,n){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&Wk(o,a)){var l=$k(o,a);return o=Tk(o,o.next),l=Tk(l,l.next),Lk(o,t,i,s,r,n),void Lk(l,t,i,s,r,n)}a=a.next}o=o.next}while(o!==e)}function Qk(e,t){return e.x-t.x}function Vk(e,t){if(t=function(e,t){var i,s=t,r=e.x,n=e.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o){if(o=a,a===r){if(n===s.y)return s;if(n===s.next.y)return s.next}i=s.x=s.x&&s.x>=A&&r!==s.x&&zk(ni.x||s.x===i.x&&Hk(i,s)))&&(i=s,h=l)),s=s.next}while(s!==u);return i}(e,t),t){var i=$k(t,e);Tk(t,t.next),Tk(i,i.next)}}function Hk(e,t){return Kk(e.prev,e,t.prev)<0&&Kk(t.next,e,e.next)<0}function jk(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*r)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-s)*r)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gk(e){var t=e,i=e;do{(t.x=0&&(e-o)*(s-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(r-o)*(s-a)>=0}function Wk(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Yk(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(qk(e,t)&&qk(t,e)&&function(e,t){var i=e,s=!1,r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(Kk(e.prev,e,t.prev)||Kk(e,t.prev,t))||Xk(e,t)&&Kk(e.prev,e,e.next)>0&&Kk(t.prev,t,t.next)>0)}function Kk(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Xk(e,t){return e.x===t.x&&e.y===t.y}function Yk(e,t,i,s){var r=Zk(Kk(e,t,i)),n=Zk(Kk(e,t,s)),o=Zk(Kk(i,s,e)),a=Zk(Kk(i,s,t));return r!==n&&o!==a||(!(0!==r||!Jk(e,i,t))||(!(0!==n||!Jk(e,s,t))||(!(0!==o||!Jk(i,e,s))||!(0!==a||!Jk(i,t,s)))))}function Jk(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Zk(e){return e>0?1:e<0?-1:0}function qk(e,t){return Kk(e.prev,e,e.next)<0?Kk(e,t,e.next)>=0&&Kk(e,e.prev,t)>=0:Kk(e,t,e.prev)<0||Kk(e,e.next,t)<0}function $k(e,t){var i=new iI(e.i,e.x,e.y),s=new iI(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function eI(e,t,i,s){var r=new iI(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function tI(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function iI(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function sI(e,t,i,s){for(var r=0,n=t,o=i-s;n0&&(s+=e[r-1].length,i.holes.push(s))}return i};var rI=$.vec2(),nI=$.vec3(),oI=$.vec3(),aI=$.vec3(),lI=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"cityJSONLoader",e,r)).dataSource=r.dataSource,s}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Ik}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new hh(this.viewer.scene,le.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;var i={};if(e.src)this._loadModel(e.src,e,i,t);else{var s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(e.cityJSON,e,i,t),s.processes--}return t}},{key:"_loadModel",value:function(e,t,i,s){var r=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getCityJSON(t.src,(function(e){r._parseModel(e,t,i,s),n.processes--}),(function(e){n.processes--,r.error(e),s.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,s){if(!s.destroyed){var r=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,n=t.stats||{};n.sourceFormat=e.type||"CityJSON",n.schemaVersion=e.version||"",n.title="",n.author="",n.created="",n.numMetaObjects=0,n.numPropertySets=0,n.numObjects=0,n.numGeometries=0,n.numTriangles=0,n.numVertices=0;var o=!1!==t.loadMetadata,a=o?{id:$.createUUID(),name:"Model",type:"Model"}:null,l=o?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,u={data:e,vertices:r,sceneModel:s,loadMetadata:o,metadata:l,rootMetaObject:a,nextId:0,stats:n};if(this._parseCityJSON(u),s.finalize(),o){var A=s.id;this.viewer.metaScene.createMetaModel(A,u.metadata,i)}s.scene.once("tick",(function(){s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}}},{key:"_transformVertices",value:function(e,t,i){for(var s=[],r=t.scale||$.vec3([1,1,1]),n=t.translate||$.vec3([0,0,0]),o=0,a=0;o0){for(var u=[],A=0,c=t.geometry.length;A0){var _=g[m[0]];if(void 0!==_.value)d=v[_.value];else{var y=_.values;if(y){p=[];for(var b=0,w=y.length;b0&&(s.createEntity({id:i,meshIds:u,isObject:!0}),e.stats.numObjects++)}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function(e,t,i,s){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var r=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,r,s);break;case"Solid":for(var n=t.boundaries,o=0;o0&&c.push(u.length);var f=this._extractLocalIndices(e,a[p],h,d);u.push.apply(u,A(f))}if(3===u.length)d.indices.push(u[0]),d.indices.push(u[1]),d.indices.push(u[2]);else if(u.length>3){for(var v=[],g=0;g0&&o.indices.length>0){var f=""+e.nextId++;r.createMesh({id:f,primitive:"triangles",positions:o.positions,indices:o.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),s.push(f),e.stats.numGeometries++,e.stats.numVertices+=o.positions.length/3,e.stats.numTriangles+=o.indices.length/3}}},{key:"_parseSurfacesWithSharedMaterial",value:function(e,t,i,s){for(var r=e.vertices,n=0;n0&&a.push(o.length);var u=this._extractLocalIndices(e,t[n][l],i,s);o.push.apply(o,A(u))}if(3===o.length)s.indices.push(o[0]),s.indices.push(o[1]),s.indices.push(o[2]);else if(o.length>3){for(var c=[],h=0;h0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getDotBIM",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}(),AI=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"DotBIMLoader",e,r)).dataSource=r.dataSource,s.objectDefaults=r.objectDefaults,s}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new uI}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0,backfaces:t.backfaces,dtxEnabled:t.dtxEnabled,rotation:t.rotation,origin:t.origin})),s=i.id;if(!t.src&&!t.dotBIM)return this.error("load() param expected: src or dotBIM"),i;var r,n,o=t.objectDefaults||this._objectDefaults||AE;if(t.includeTypes){r={};for(var a=0,l=t.includeTypes.length;a=0?A:2*Math.PI-A}return r0||o>0||a>0))}}(),n=[],o=(s?t:t.slice(0).reverse()).map((function(e){return{idx:e}}));o.forEach((function(e,t){e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));for(var a=$.vec2(),l=$.vec2();o.length>2;){for(var u=0,A=function(){if(u>=o.length)throw"isCCW = ".concat(s,"; earIdx = ").concat(u,"; len = ").concat(o.length);var t=o[u],i=e[t.prev.idx],n=e[t.idx],A=e[t.next.idx];if($.subVec2(i,n,a),$.subVec2(A,n,l),a[0]*l[1]-a[1]*l[0]>=0&&o.every((function(s){return s===t||s===t.prev||s===t.next||!r(e[s.idx],i,n,A)})))return"break";++u};;){if("break"===A())break}var c=o[u];o.splice(u,1),n.push([c.idx,c.next.idx,c.prev.idx]),c.prev.next=c.next,c.next.prev=c.prev}return[e,n]},pI=function(e,t,i,s,r,n,o,a,l){var u,c=i.scene,h=c.canvas.canvas,d=new et(c,{}),p=function(e){var t=$.vec2([e.clientX,e.clientY]);hI(h.ownerDocument.body,h,t);var i=function(e){var t=$.vec3(),i=$.vec3();return $.canvasPosToWorldRay(h,c.camera.viewMatrix,c.camera.projMatrix,e,t,i),n(t,i)}(t);d.worldPos=i,B(),a(t,i)},f=null,v=function(e){var t=f.matchesEvent(e);t&&p(t)},g=function(e){var t=f.matchesEvent(e);t&&(b.setOpacity(w),f.cleanup(),p(t),l())},m=function(e,t){f&&f.cleanup(),b.setOpacity(1),b.setClickable(!1),i.cameraControl.active=!1,f={matchesEvent:e,cleanup:function(){f=null,b.setClickable(!0),i.cameraControl.active=!0,t()}},o()},_={fillColor:r};(e&&(_.onMouseOver=function(){return!f&&b.setOpacity(1)},_.onMouseLeave=function(){return!f&&b.setOpacity(w)},_.onMouseDown=function(e){1===e.which&&(h.addEventListener("mousemove",v),h.addEventListener("mouseup",g),m((function(e){return 1===e.which&&e}),(function(){h.removeEventListener("mousemove",v),h.removeEventListener("mouseup",g)})))}),t)&&(_.onTouchstart=function(e){e.preventDefault(),1===e.touches.length&&(u=e.touches[0].identifier,m((function(e){return A(e.changedTouches).find((function(e){return e.identifier===u}))}),(function(){u=null})))},_.onTouchmove=function(e){e.preventDefault(),v(e)},_.onTouchend=function(e){e.preventDefault(),g(e)});var y=h.ownerDocument.body,b=new st(y,_),w=.5;b.setOpacity(w);var B=function(){var e=d.canvasPos.slice();hI(h,y,e),b.setPos(e[0],e[1])};d.worldPos=s,B();var x=c.camera.on("viewMatrix",B),P=c.camera.on("projMatrix",B);return{setActive:function(e){return b.setClickable(e)},getWorldPos:function(){return d.worldPos},setWorldPos:function(e){d.worldPos=e,B()},destroy:function(){f&&f.cleanup(),c.camera.off(x),c.camera.off(P),d.destroy(),b.destroy()}}},fI=function(e,t){var i=e.canvas.canvas,s=i.parentNode,r=document.createElement("div");s.insertBefore(r,i);var n=5;r.style.background=t,r.style.border="2px solid white",r.style.margin="0 0",r.style.zIndex="100",r.style.position="absolute",r.style.pointerEvents="none",r.style.display="none";var o=new et(e,{}),a=function(e){return e+"px"},l=function(){var e=o.canvasPos.slice();hI(i,s,e),r.style.left=a(e[0]-3-n/2),r.style.top=a(e[1]-3-n/2),r.style.borderRadius=a(2*n),r.style.width=a(n),r.style.height=a(n)},u=e.camera.on("viewMatrix",l),A=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),r.style.display=e?"":"none"},setHighlighted:function(e){n=e?10:5,l()},getCanvasPos:function(){return o.canvasPos},getWorldPos:function(){return o.worldPos},destroy:function(){r.parentNode.removeChild(r),e.camera.off(u),e.camera.off(A),o.destroy()}}},vI=function(e,t,i){var s=null,r=function(r){if(r){s&&s.destroy();try{var n,o,a=dI(r.map((function(e){return[e[0],e[2]]}))),l=h(a,2),u=l[0],c=l[1],d=(n=[]).concat.apply(n,A(u.map((function(e){return[e[0],r[0][1],e[1]]})))),p=(o=[]).concat.apply(o,A(c));s=new nn(e,{pickable:!1,geometry:new Ti(e,{positions:d,indices:p,normals:$.buildNormals(d,p)}),material:new Ni(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:cI(t)})})}catch(e){s=null}}s&&(s.visible=!!r)};return r(null),{updateBase:r,destroy:function(){return s&&s.destroy()}}},gI=function(e,t,i,s,r,n,o,a,l){var u=fI(e,s),A=fI(e,s),c=vI(e,s,r),h=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},d=a((function(){h(null),u.update(null)}),(function(e,t){h(e),u.update(t)}),(function(e,n){u.update(n),d=a((function(){h(null),A.update(null),c.updateBase(null)}),(function(e,t){if(h(e),A.update(t),$.distVec3(n,t)>.01){var i=function(e){return Math.min(n[e],t[e])},s=function(e){return Math.max(n[e],t[e])},r=i(0),o=i(1),a=i(2),l=s(0);s(1);var u=s(2);c.updateBase([[r,o,u],[l,o,u],[l,o,a],[r,o,a]])}else c.updateBase(null)}),(function(e,a){A.update(a),u.destroy(),A.destroy(),c.destroy(),h(null);var d=function(e){return Math.min(n[e],a[e])},p=function(e){return Math.max(n[e],a[e])},f=d(0),v=d(2),g=p(0),m=p(2),_=o.createZone({id:$.createUUID(),geometry:{planeCoordinates:[[f,m],[g,m],[g,v],[f,v]],altitude:t,height:i},alpha:r,color:s});l(_)}))}));return{deactivate:function(){d(),u.destroy(),A.destroy(),c.destroy(),h(null)}}},mI=function(e,t){return function(i,s,r){var n=e.scene,o=n.canvas.canvas,a=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(o.ownerDocument.body,o,t),t},l=function(e){var i=$.vec3(),s=$.vec3();return $.canvasPosToWorldRay(o,n.camera.viewMatrix,n.camera.projMatrix,e,i,s),t(i,s)},u=!1,A=function(){u=!1},c=function(){A(),o.removeEventListener("mousedown",d),o.removeEventListener("mousemove",p),e.cameraControl.off(f),o.removeEventListener("mouseup",v)},h=$.vec2(),d=function(e){1===e.which&&(a(e,h),u=!0)};o.addEventListener("mousedown",d);var p=function(e){var t=a(e,$.vec2());u&&$.distVec2(h,t)>20&&(A(),i())};o.addEventListener("mousemove",p);var f=e.cameraControl.on("rayMove",(function(e){var t=e.canvasPos;s(t,l(t))})),v=function(e){if(1===e.which&&u){c();var t=a(e,$.vec2());r(t,l(t))}};return o.addEventListener("mouseup",v),c}},_I=function(e,t,i){return function(s,r,n){var o,a=e.scene,l=a.canvas.canvas,u=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(l.ownerDocument.body,l,t),t},c=function(e){var t=$.vec3(),s=$.vec3();return $.canvasPosToWorldRay(l,a.camera.viewMatrix,a.camera.projMatrix,e,t,s),i(t,s)},h=null,d=function(){},p=d,f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=d,o=null},v=function(){f(),l.removeEventListener("touchstart",g),l.removeEventListener("touchmove",m),l.removeEventListener("touchend",_)},g=function(i){var n=i.touches;if(1!==n.length)f(),s();else{var a=n[0],l=u(a,$.vec2());c(l)&&(o=a.identifier,p=function(e){$.distVec2(l,e)>20&&f()},h=setTimeout((function(){t.start(l),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=function(e){r(e,c(e))},p(l)}),300)}),250))}};l.addEventListener("touchstart",g,{passive:!0});var m=function(e){var t=A(e.changedTouches).find((function(e){return e.identifier===o}));t&&p(u(t,$.vec2()))};l.addEventListener("touchmove",m,{passive:!0});var _=function(e){var t=A(e.changedTouches).find((function(e){return e.identifier===o}));if(t){v();var i=u(t,$.vec2());n(i,c(i))}};return l.addEventListener("touchend",_,{passive:!0}),v}},yI=function(e,t,i,s){var r=-($.dotVec3(i,t)-e)/$.dotVec3(s,t),n=$.vec3();return $.mulVec3Scalar(s,r,n),$.addVec3(i,n,n),n},bI=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(s=t.call(this,e.viewer.scene,r)).plugin=e,s._container=r.container,!s._container)throw"config missing: container";return s._eventSubs={},s.plugin.viewer.scene,s._geometry=r.geometry,r.onMouseOver,r.onMouseLeave,r.onContextMenu,s._alpha="alpha"in r&&void 0!==r.alpha?r.alpha:.5,s.color=r.color,s._visible=!0,s._rebuildMesh(),s}return C(i,[{key:"_rebuildMesh",value:function(){var e,t=this.plugin.viewer.scene,i=this._geometry.planeCoordinates.slice(),s=this._geometry.height<0,r=this._geometry.altitude+(s?this._geometry.height:0),n=this._geometry.height*(s?-1:1),o=h(dI(i),2),a=o[0],l=o[1],u=[],d=[],p=function(e){var t,i=u.length,s=c(a);try{for(s.s();!(t=s.n()).done;){var o=t.value;u.push([o[0],r+(e?n:0),o[1]])}}catch(e){s.e(e)}finally{s.f()}var h,p=c(l);try{for(p.s();!(h=p.n()).done;){var f=h.value;d.push.apply(d,A((e?f:f.slice(0).reverse()).map((function(e){return e+i}))))}}catch(e){p.e(e)}finally{p.f()}};p(!1),p(!0);for(var f=function(e){var t=a[e],i=a[(e+1)%a.length],s=r,o=r+n,l=u.length;u.push([t[0],s,t[1]],[i[0],s,i[1]],[i[0],o,i[1]],[t[0],o,t[1]]),d.push.apply(d,A([0,1,2,0,2,3].map((function(e){return e+l}))))},v=0;vb?1:0;w|=C,B.push(C)}switch(w){case 0:case 1:m.push(y);break;case 2:break;case 3:for(var M=[],E=0;E=3&&m.push(M)}}}catch(e){_.e(e)}finally{_.f()}i=m}}catch(e){d.e(e)}finally{d.f()}if(0===i.length)return null;var U,O=$.vec3([0,0,0]),N=new Set,Q=c(i);try{for(Q.s();!(U=Q.n()).done;){var V,H=c(U.value);try{for(H.s();!(V=H.n()).done;){var j=V.value,G=j.map((function(e){return e.toFixed(3)})).join(":");N.has(G)||(N.add(G),$.addVec3(O,j,O))}}catch(e){H.e(e)}finally{H.f()}}}catch(e){Q.e(e)}finally{Q.f()}return $.mulVec3Scalar(O,1/N.size,O),O}},{key:"center",get:function(){return this._center}},{key:"altitude",get:function(){return this._geometry.altitude},set:function(e){this._geometry.altitude=e,this._rebuildMesh()}},{key:"height",get:function(){return this._geometry.height},set:function(e){this._geometry.height=e,this._rebuildMesh()}},{key:"highlighted",get:function(){return this._highlighted},set:function(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=cI(this._color))}},{key:"alpha",get:function(){return this._alpha},set:function(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}},{key:"edges",get:function(){return this._edges},set:function(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}},{key:"getJSON",value:function(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}},{key:"duplicate",value:function(){return this.plugin.createZone({id:$.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((function(e){return e.slice()})),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}},{key:"destroy",value:function(){this._zoneMesh.destroy(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),wI=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene)).zonesPlugin=e,s.pointerLens=r.pointerLens,s._deactivate=null,s}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,s){if(!this._deactivate){if("object"===B(e)&&null!==e){var r=e,n=function(e,t){if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),s=n("alpha",.5)}var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=mI(a,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function r(){u._deactivate=gI(l,e,t,i,s,u.pointerLens,o,A,(function(e){var t=!0;u._deactivate=function(){t=!1},u.fire("zoneEnd",e),t&&r()})).deactivate}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),BI=function(e){g(i,Se);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,"Zones",e))._pointerLens=r.pointerLens,s._container=r.container||document.body,s._zones=[],s.defaultColor=void 0!==r.defaultColor?r.defaultColor:"#00BBFF",s.zIndex=r.zIndex||1e4,s._onMouseOver=function(e,t){s.fire("mouseOver",{plugin:b(s),zone:t,event:e})},s._onMouseLeave=function(e,t){s.fire("mouseLeave",{plugin:b(s),zone:t,event:e})},s._onContextMenu=function(e,t){s.fire("contextMenu",{plugin:b(s),zone:t,event:e})},s}return C(i,[{key:"createZone",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=new bI(this,{id:t.id,plugin:this,container:this._container,geometry:t.geometry,alpha:t.alpha,color:t.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(i),i.on("destroyed",(function(){var t=e._zones.indexOf(i);t>=0&&e._zones.splice(t,1)})),this.fire("zoneCreated",i),i}},{key:"zones",get:function(){return this._zones}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),xI=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene)).zonesPlugin=e,s.pointerLens=r.pointerLens,s.pointerCircle=new De(e.viewer),s._deactivate=null,s}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,s){if("object"===B(e)&&null!==e){var r=e,n=function(e,t){if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),s=n("alpha",.5)}if(!this._deactivate){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=_I(a,this.pointerCircle,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function r(){u._deactivate=gI(l,e,t,i,s,u.pointerLens,o,A,(function(e){var t=!0;u._deactivate=function(){t=!1},u.fire("zoneEnd",e),t&&r()})).deactivate}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),PI=function(e,t,i,s,r,n,o,a,l){var u,A=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},c=[function(){return A(null)}],h=vI(e,s,r);return c.push((function(){return h.destroy()})),function n(d){var p=fI(e,s),f=d.length>0&&function(e,t,i){var s=e.canvas.canvas,r=new et(e,{});r.worldPos=i;var n=new et(e,{}),o=s.ownerDocument.body,a=new it(o,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);var l=function(){var e=r.canvasPos.slice(),t=n.canvasPos.slice();hI(s,o,e),hI(s,o,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},u=e.camera.on("viewMatrix",l),A=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(u),e.camera.off(A),r.destroy(),n.destroy(),a.destroy()}}}(e,s,d[d.length-1].getWorldPos());c.push((function(){p.destroy(),f&&f.destroy()}));var v=d.length>0&&d[0],g=function(e){var t=v&&v.getCanvasPos();return t&&$.distVec2(t,e)<10&&{canvasPos:t,worldPos:v.getWorldPos()}},m=function(){var e=function(e,t,i){return t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1])},t=function(e,t,i){var s=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===s?0:s>0?1:2};return function(i,s){for(var r=i[i.length-2],n=i[i.length-1],o=s?1:0;o2?d.map((function(e){return e.getWorldPos()})):null)}),(function(e,t){var i=d.length>2&&g(e);if(v&&v.setHighlighted(!!i),A(i?i.canvasPos:e),p.update(!i&&t),f&&f.update(i?i.worldPos:t),d.length>=2){var s=d.map((function(e){return e.getWorldPos()})).concat(i?[]:[t]),r=m(s.map((function(e){return[e[0],e[2]]})),i);h.updateBase(r?null:s)}else h.updateBase(null)}),(function(e,a){var u=d.length>2&&g(e),A=d.map((function(e){return e.getWorldPos()})).concat(u?[]:[a]);h.updateBase(A);var v=A.map((function(e){return[e[0],e[2]]}));d.length>2&&m(v,u)?(c.pop()(),n(d)):u?(p.update(a),c.forEach((function(e){return e()})),l(o.createZone({id:$.createUUID(),geometry:{planeCoordinates:v,altitude:t,height:i},alpha:r,color:s}))):(p.update(a),f&&f.update(a),n(d.concat(p)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){u(),c.forEach((function(e){return e()}))}}},CI=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene)).zonesPlugin=e,s.pointerLens=r.pointerLens,s._action=null,s}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,s){if("object"===B(e)&&null!==e){var r=e,n=function(e,t){if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),s=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=mI(a,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function r(){u._action=PI(l,e,t,i,s,u.pointerLens,o,A,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&r()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),MI=function(e){g(i,we);var t=_(i);function i(e){var s,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(s=t.call(this,e.viewer.scene)).zonesPlugin=e,s.pointerLens=r.pointerLens,s.pointerCircle=new De(e.viewer),s._action=null,s}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,s){if("object"===B(e)&&null!==e){var r=e,n=function(e,t){if(e in r)return r[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),s=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=_I(a,this.pointerCircle,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function r(){u._action=PI(l,e,t,i,s,u.pointerLens,o,A,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&r()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),EI=function(e){g(i,we);var t=_(i);function i(e,s,r,n){var o;x(this,i);var a=b(o=t.call(this,e.plugin.viewer.scene)),l=e._geometry.altitude,u=s&&s.pointerLens,A=u?function(e){u.visible=!!e,e&&(u.canvasPos=e)}:function(){},c=e._geometry.planeCoordinates.map((function(t){var i,s,o=function(i){t[0]=i[0],t[1]=i[1];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}},u=pI(r,n,e.plugin.viewer,$.vec3([t[0],l,t[1]]),e._color,(function(e,t){return yI(l,$.vec3([0,1,0]),e,t)}),(function(){i=u.getWorldPos().slice(),s=t.slice(),h(!1,u)}),(function(e,t){A(e),o([t[0],t[2]])}),(function(){e._zoneMesh?a.fire("edited"):(u.setWorldPos(i),o(s)),A(null),h(!0,u)}));return u})),h=function(e,t){return c.forEach((function(i){return i!==t&&i.setActive(e)}))};h(!0);var d=function(){c.forEach((function(e){return e.destroy()})),A(null)},p=e.on("destroyed",d);return o._deactivate=function(){e.off("destroyed",p),d()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),FI=function(e){g(i,EI);var t=_(i);function i(e,s){return x(this,i),t.call(this,e,s,!0,!1)}return C(i)}(),kI=function(e){g(i,EI);var t=_(i);function i(e,s){return x(this,i),t.call(this,e,s,!1,!0)}return C(i)}(),II=function(e){g(i,we);var t=_(i);function i(e,s,r,n){var o;x(this,i);var a=e.plugin.viewer,l=a.scene,u=l.canvas.canvas,c=b(o=t.call(this,l)),h=e._geometry.altitude,d=s&&s.pointerLens,p=d?function(e){d.visible=!!e,e&&(d.canvasPos=e)}:function(){},f=function(e){var t,i,s=$.vec3(),r=$.vec3();return $.canvasPosToWorldRay(u,l.camera.viewMatrix,l.camera.projMatrix,e,s,r),t=s,i=r,yI(h,$.vec3([0,1,0]),t,i)},v=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(u.ownerDocument.body,u,t),t},g=function(e,t){var i=function(e){e.preventDefault(),t(e)};return u.addEventListener(e,i),function(){return u.removeEventListener(e,i)}},m=function(){},_=function(t,i,s,r){var n,o,l,A,h=r(t),d=v(h,$.vec2()),_=a.scene.pick({canvasPos:d,includeEntities:[e._zoneMesh.id]});if((_&&_.entity&&_.entity.zone)===e){m(),u.style.cursor="move",a.cameraControl.active=!1;var y=(n=e._geometry.planeCoordinates.map((function(e){return e.slice()})),o=f(d),l=$.vec2([o[0],o[2]]),A=$.vec2(),function(t){var i=f(t);A[0]=i[0],A[1]=i[2],$.subVec2(l,A,A),e._geometry.planeCoordinates.forEach((function(e,t){$.subVec2(n[t],A,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}),b=g(i,(function(e){var t=r(e);if(t){var i=v(t,$.vec2());y(i),p(i)}})),w=g(s,(function(e){var t=r(e);if(t){var i=v(t,$.vec2());y(i),p(null),m(),c.fire("translated")}}));m=function(){m=function(){},u.style.cursor="default",a.cameraControl.active=!0,b(),w()}}},y=[];r&&y.push(g("mousedown",(function(e){1===e.which&&_(e,"mousemove","mouseup",(function(e){return 1===e.which&&e}))}))),n&&y.push(g("touchstart",(function(e){if(1===e.touches.length){var t=e.touches[0].identifier;_(e,"touchmove","touchend",(function(e){return A(e.changedTouches).find((function(e){return e.identifier===t}))}))}})));var w=function(){m(),y.forEach((function(e){return e()})),p(null)},B=e.on("destroyed",w);return o._deactivate=function(){e.off("destroyed",B),w()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),DI=function(e){g(i,II);var t=_(i);function i(e,s){return x(this,i),t.call(this,e,s,!0,!1)}return C(i)}(),SI=function(e){g(i,II);var t=_(i);function i(e,s){return x(this,i),t.call(this,e,s,!1,!0)}return C(i)}();export{xs as AlphaFormat,wi as AmbientLight,lt as AngleMeasurementsControl,ut as AngleMeasurementsMouseControl,At as AngleMeasurementsPlugin,ct as AngleMeasurementsTouchControl,vt as AnnotationsPlugin,cn as AxisGizmoPlugin,_h as BCFViewpointsPlugin,$n as Bitmap,ps as ByteType,od as CameraMemento,Qh as CameraPath,Kh as CameraPathAnimation,lI as CityJSONLoaderPlugin,ts as ClampToEdgeWrapping,we as Component,dr as CompressedMediaType,Yo as Configs,z as ContextMenu,cd as CubicBezierCurve,Uh as Curve,kc as DefaultLoadingManager,Fs as DepthFormat,ks as DepthStencilFormat,bi as DirLight,Eh as DistanceMeasurementsControl,Fh as DistanceMeasurementsMouseControl,kh as DistanceMeasurementsPlugin,Ih as DistanceMeasurementsTouchControl,uI as DotBIMDefaultDataSource,AI as DotBIMLoaderPlugin,ji as EdgeMaterial,Vi as EmphasisMaterial,KE as FaceAlignedSectionPlanesPlugin,Dh as FastNavPlugin,_s as FloatType,Nn as Fresnel,Me as Frustum,Ce as FrustumPlane,Ar as GIFMediaType,Sh as GLTFDefaultDataSource,cE as GLTFLoaderPlugin,ys as HalfFloatType,qh as ImagePlane,gs as IntType,cr as JPEGMediaType,Rc as KTX2TextureTranscoder,Fk as LASLoaderPlugin,Bn as LambertMaterial,rd as LightMap,ph as LineSet,lr as LinearEncoding,ls as LinearFilter,hs as LinearMipMapLinearFilter,As as LinearMipMapNearestFilter,cs as LinearMipmapLinearFilter,us as LinearMipmapNearestFilter,Ic as Loader,Fc as LoadingManager,Th as LocaleService,Es as LuminanceAlphaFormat,Ms as LuminanceFormat,Q as Map,et as Marker,ke as MarqueePicker,Ie as MarqueePickerMouseControl,nn as Mesh,Cn as MetallicMaterial,is as MirroredRepeatWrapping,ld as ModelMemento,fE as NavCubePlugin,ss as NearestFilter,as as NearestMipMapLinearFilter,rs as NearestMipMapNearestFilter,os as NearestMipmapLinearFilter,ns as NearestMipmapNearestFilter,wn as Node,PE as OBJLoaderPlugin,te as ObjectsKdTree3,Ad as ObjectsMemento,hr as PNGMediaType,hd as Path,pd as PerformanceModel,Ni as PhongMaterial,xt as PickResult,Se as Plugin,$h as PointLight,De as PointerCircle,W as PointerLens,dd as QuadraticBezierCurve,ie as Queue,Cs as RGBAFormat,Ls as RGBAIntegerFormat,rr as RGBA_ASTC_10x10_Format,tr as RGBA_ASTC_10x5_Format,ir as RGBA_ASTC_10x6_Format,sr as RGBA_ASTC_10x8_Format,nr as RGBA_ASTC_12x10_Format,or as RGBA_ASTC_12x12_Format,Ks as RGBA_ASTC_4x4_Format,Xs as RGBA_ASTC_5x4_Format,Ys as RGBA_ASTC_5x5_Format,Js as RGBA_ASTC_6x5_Format,Zs as RGBA_ASTC_6x6_Format,qs as RGBA_ASTC_8x5_Format,$s as RGBA_ASTC_8x6_Format,er as RGBA_ASTC_8x8_Format,ar as RGBA_BPTC_Format,Ws as RGBA_ETC2_EAC_Format,js as RGBA_PVRTC_2BPPV1_Format,Hs as RGBA_PVRTC_4BPPV1_Format,Us as RGBA_S3TC_DXT1_Format,Os as RGBA_S3TC_DXT3_Format,Ns as RGBA_S3TC_DXT5_Format,Ps as RGBFormat,Gs as RGB_ETC1_Format,zs as RGB_ETC2_Format,Vs as RGB_PVRTC_2BPPV1_Format,Qs as RGB_PVRTC_4BPPV1_Format,Rs as RGB_S3TC_DXT1_Format,Ss as RGFormat,Ts as RGIntegerFormat,Ti as ReadableGeometry,Is as RedFormat,Ds as RedIntegerFormat,sd as ReflectionMap,es as RepeatWrapping,YE as STLDefaultDataSource,rF as STLLoaderPlugin,hh as SceneModel,so as SceneModelMesh,sh as SceneModelTransform,hn as SectionPlane,SE as SectionPlanesPlugin,fs as ShortType,fd as Skybox,XE as SkyboxesPlugin,Fn as SpecularMaterial,Oh as SplineCurve,nd as SpriteMarker,NE as StoreyViewsPlugin,On as Texture,vd as TextureTranscoder,aF as TreeViewPlugin,ds as UnsignedByteType,Bs as UnsignedInt248Type,ms as UnsignedIntType,bs as UnsignedShort4444Type,ws as UnsignedShort5551Type,vs as UnsignedShortType,Hn as VBOGeometry,hF as ViewCullPlugin,nb as Viewer,bk as WebIFCLoaderPlugin,Tc as WorkerPool,dF as XKTDefaultDataSource,sk as XKTLoaderPlugin,_k as XML3DLoaderPlugin,EI as ZoneEditControl,FI as ZoneEditMouseControl,kI as ZoneEditTouchControl,II as ZoneTranslateControl,DI as ZoneTranslateMouseControl,SI as ZoneTranslateTouchControl,wI as ZonesMouseControl,BI as ZonesPlugin,CI as ZonesPolysurfaceMouseControl,MI as ZonesPolysurfaceTouchControl,xI as ZonesTouchControl,Li as buildBoxGeometry,Wn as buildBoxLinesGeometry,Kn as buildBoxLinesGeometryFromAABB,an as buildCylinderGeometry,Xn as buildGridGeometry,Yn as buildPlaneGeometry,Zn as buildPolylineGeometry,qn as buildPolylineGeometryFromCurve,ln as buildSphereGeometry,Jn as buildTorusGeometry,An as buildVectorTextGeometry,Le as createRTCViewMat,Fe as frustumIntersectsAABB3,Oc as getKTX2TextureTranscoder,Ne as getPlaneRTCPos,Gn as load3DSGeometry,zn as loadOBJGeometry,$ as math,Oe as rtcToWorldPos,ur as sRGBEncoding,Ee as setFrustum,se as stats,le as utils,Re as worldToRTCPos,Ue as worldToRTCPositions}; +***************************************************************************** */var op=function(e,t){return op=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},op(e,t)};function ap(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}op(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}var lp=function(){return lp=Object.assign||function(e){for(var t,i=1,r=arguments.length;i0&&s[s.length-1])||6!==n[0]&&2!==n[0])){o=0;continue}if(3===n[0]&&(!s||n[1]>s[0]&&n[1]=55296&&s<=56319&&i>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},vp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),mp=0;mp=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),xp="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Pp="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Cp=0;Cp>4,A[l++]=(15&r)<<4|s>>2,A[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r0;){var o=r[--n];if(Array.isArray(e)?-1!==e.indexOf(o):e===o)for(var a=i;a<=r.length;){var l;if((l=r[++a])===t)return!0;if(l!==Mp)break}if(o!==Mp)break}return!1},lf=function(e,t){for(var i=e;i>=0;){var r=t[i];if(r!==Mp)return r;i--}return 0},uf=function(e,t,i,r,s){if(0===i[r])return"×";var n=r-1;if(Array.isArray(s)&&!0===s[n])return"×";var o=n-1,a=n+1,l=t[n],u=o>=0?t[o]:0,A=t[a];if(2===l&&3===A)return"×";if(-1!==ef.indexOf(l))return"!";if(-1!==ef.indexOf(A))return"×";if(-1!==tf.indexOf(A))return"×";if(8===lf(n,t))return"÷";if(11===qp.get(e[n]))return"×";if((l===Hp||l===jp)&&11===qp.get(e[a]))return"×";if(7===l||7===A)return"×";if(9===l)return"×";if(-1===[Mp,Ep,Fp].indexOf(l)&&9===A)return"×";if(-1!==[kp,Ip,Dp,Rp,Qp].indexOf(A))return"×";if(lf(n,t)===Lp)return"×";if(af(23,Lp,n,t))return"×";if(af([kp,Ip],Tp,n,t))return"×";if(af(12,12,n,t))return"×";if(l===Mp)return"÷";if(23===l||23===A)return"×";if(16===A||16===l)return"÷";if(-1!==[Ep,Fp,Tp].indexOf(A)||14===l)return"×";if(36===u&&-1!==of.indexOf(l))return"×";if(l===Qp&&36===A)return"×";if(A===Sp)return"×";if(-1!==$p.indexOf(A)&&l===Up||-1!==$p.indexOf(l)&&A===Up)return"×";if(l===Np&&-1!==[Wp,Hp,jp].indexOf(A)||-1!==[Wp,Hp,jp].indexOf(l)&&A===Op)return"×";if(-1!==$p.indexOf(l)&&-1!==rf.indexOf(A)||-1!==rf.indexOf(l)&&-1!==$p.indexOf(A))return"×";if(-1!==[Np,Op].indexOf(l)&&(A===Up||-1!==[Lp,Fp].indexOf(A)&&t[a+1]===Up)||-1!==[Lp,Fp].indexOf(l)&&A===Up||l===Up&&-1!==[Up,Qp,Rp].indexOf(A))return"×";if(-1!==[Up,Qp,Rp,kp,Ip].indexOf(A))for(var c=n;c>=0;){if((h=t[c])===Up)return"×";if(-1===[Qp,Rp].indexOf(h))break;c--}if(-1!==[Np,Op].indexOf(A))for(c=-1!==[kp,Ip].indexOf(l)?o:n;c>=0;){var h;if((h=t[c])===Up)return"×";if(-1===[Qp,Rp].indexOf(h))break;c--}if(Kp===l&&-1!==[Kp,Xp,Gp,zp].indexOf(A)||-1!==[Xp,Gp].indexOf(l)&&-1!==[Xp,Yp].indexOf(A)||-1!==[Yp,zp].indexOf(l)&&A===Yp)return"×";if(-1!==nf.indexOf(l)&&-1!==[Sp,Op].indexOf(A)||-1!==nf.indexOf(A)&&l===Np)return"×";if(-1!==$p.indexOf(l)&&-1!==$p.indexOf(A))return"×";if(l===Rp&&-1!==$p.indexOf(A))return"×";if(-1!==$p.concat(Up).indexOf(l)&&A===Lp&&-1===Zp.indexOf(e[a])||-1!==$p.concat(Up).indexOf(A)&&l===Ip)return"×";if(41===l&&41===A){for(var d=i[n],p=1;d>0&&41===t[--d];)p++;if(p%2!=0)return"×"}return l===Hp&&A===jp?"×":"÷"},Af=function(e,t){t||(t={lineBreak:"normal",wordBreak:"normal"});var i=function(e,t){void 0===t&&(t="strict");var i=[],r=[],s=[];return e.forEach((function(e,n){var o=qp.get(e);if(o>50?(s.push(!0),o-=50):s.push(!1),-1!==["normal","auto","loose"].indexOf(t)&&-1!==[8208,8211,12316,12448].indexOf(e))return r.push(n),i.push(16);if(4===o||11===o){if(0===n)return r.push(n),i.push(Vp);var a=i[n-1];return-1===sf.indexOf(a)?(r.push(r[n-1]),i.push(a)):(r.push(n),i.push(Vp))}return r.push(n),31===o?i.push("strict"===t?Tp:Wp):o===Jp||29===o?i.push(Vp):43===o?e>=131072&&e<=196605||e>=196608&&e<=262141?i.push(Wp):i.push(Vp):void i.push(o)})),[r,i,s]}(e,t.lineBreak),r=i[0],s=i[1],n=i[2];"break-all"!==t.wordBreak&&"break-word"!==t.wordBreak||(s=s.map((function(e){return-1!==[Up,Vp,Jp].indexOf(e)?Wp:e})));var o="keep-all"===t.wordBreak?n.map((function(t,i){return t&&e[i]>=19968&&e[i]<=40959})):void 0;return[r,s,o]},cf=function(){function e(e,t,i,r){this.codePoints=e,this.required="!"===t,this.start=i,this.end=r}return e.prototype.slice=function(){return fp.apply(void 0,this.codePoints.slice(this.start,this.end))},e}(),hf=function(e){return e>=48&&e<=57},df=function(e){return hf(e)||e>=65&&e<=70||e>=97&&e<=102},pf=function(e){return 10===e||9===e||32===e},ff=function(e){return function(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}(e)||function(e){return e>=128}(e)||95===e},vf=function(e){return ff(e)||hf(e)||45===e},gf=function(e){return e>=0&&e<=8||11===e||e>=14&&e<=31||127===e},mf=function(e,t){return 92===e&&10!==t},_f=function(e,t,i){return 45===e?ff(t)||mf(t,i):!!ff(e)||!(92!==e||!mf(e,t))},yf=function(e,t,i){return 43===e||45===e?!!hf(t)||46===t&&hf(i):hf(46===e?t:e)},bf=function(e){var t=0,i=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(i=-1),t++);for(var r=[];hf(e[t]);)r.push(e[t++]);var s=r.length?parseInt(fp.apply(void 0,r),10):0;46===e[t]&&t++;for(var n=[];hf(e[t]);)n.push(e[t++]);var o=n.length,a=o?parseInt(fp.apply(void 0,n),10):0;69!==e[t]&&101!==e[t]||t++;var l=1;43!==e[t]&&45!==e[t]||(45===e[t]&&(l=-1),t++);for(var u=[];hf(e[t]);)u.push(e[t++]);var A=u.length?parseInt(fp.apply(void 0,u),10):0;return i*(s+a*Math.pow(10,-o))*Math.pow(10,l*A)},wf={type:2},Bf={type:3},xf={type:4},Pf={type:13},Cf={type:8},Mf={type:21},Ef={type:9},Ff={type:10},kf={type:11},If={type:12},Df={type:14},Sf={type:23},Tf={type:1},Lf={type:25},Rf={type:24},Uf={type:26},Of={type:27},Nf={type:28},Qf={type:29},Vf={type:31},Hf={type:32},jf=function(){function e(){this._value=[]}return e.prototype.write=function(e){this._value=this._value.concat(pp(e))},e.prototype.read=function(){for(var e=[],t=this.consumeToken();t!==Hf;)e.push(t),t=this.consumeToken();return e},e.prototype.consumeToken=function(){var e=this.consumeCodePoint();switch(e){case 34:return this.consumeStringToken(34);case 35:var t=this.peekCodePoint(0),i=this.peekCodePoint(1),r=this.peekCodePoint(2);if(vf(t)||mf(i,r)){var s=_f(t,i,r)?2:1;return{type:5,value:this.consumeName(),flags:s}}break;case 36:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Pf;break;case 39:return this.consumeStringToken(39);case 40:return wf;case 41:return Bf;case 42:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Df;break;case 43:if(yf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 44:return xf;case 45:var n=e,o=this.peekCodePoint(0),a=this.peekCodePoint(1);if(yf(n,o,a))return this.reconsumeCodePoint(e),this.consumeNumericToken();if(_f(n,o,a))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();if(45===o&&62===a)return this.consumeCodePoint(),this.consumeCodePoint(),Rf;break;case 46:if(yf(e,this.peekCodePoint(0),this.peekCodePoint(1)))return this.reconsumeCodePoint(e),this.consumeNumericToken();break;case 47:if(42===this.peekCodePoint(0))for(this.consumeCodePoint();;){var l=this.consumeCodePoint();if(42===l&&47===(l=this.consumeCodePoint()))return this.consumeToken();if(-1===l)return this.consumeToken()}break;case 58:return Uf;case 59:return Of;case 60:if(33===this.peekCodePoint(0)&&45===this.peekCodePoint(1)&&45===this.peekCodePoint(2))return this.consumeCodePoint(),this.consumeCodePoint(),Lf;break;case 64:var u=this.peekCodePoint(0),A=this.peekCodePoint(1),c=this.peekCodePoint(2);if(_f(u,A,c))return{type:7,value:this.consumeName()};break;case 91:return Nf;case 92:if(mf(e,this.peekCodePoint(0)))return this.reconsumeCodePoint(e),this.consumeIdentLikeToken();break;case 93:return Qf;case 61:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Cf;break;case 123:return kf;case 125:return If;case 117:case 85:var h=this.peekCodePoint(0),d=this.peekCodePoint(1);return 43!==h||!df(d)&&63!==d||(this.consumeCodePoint(),this.consumeUnicodeRangeToken()),this.reconsumeCodePoint(e),this.consumeIdentLikeToken();case 124:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Ef;if(124===this.peekCodePoint(0))return this.consumeCodePoint(),Mf;break;case 126:if(61===this.peekCodePoint(0))return this.consumeCodePoint(),Ff;break;case-1:return Hf}return pf(e)?(this.consumeWhiteSpace(),Vf):hf(e)?(this.reconsumeCodePoint(e),this.consumeNumericToken()):ff(e)?(this.reconsumeCodePoint(e),this.consumeIdentLikeToken()):{type:6,value:fp(e)}},e.prototype.consumeCodePoint=function(){var e=this._value.shift();return void 0===e?-1:e},e.prototype.reconsumeCodePoint=function(e){this._value.unshift(e)},e.prototype.peekCodePoint=function(e){return e>=this._value.length?-1:this._value[e]},e.prototype.consumeUnicodeRangeToken=function(){for(var e=[],t=this.consumeCodePoint();df(t)&&e.length<6;)e.push(t),t=this.consumeCodePoint();for(var i=!1;63===t&&e.length<6;)e.push(t),t=this.consumeCodePoint(),i=!0;if(i)return{type:30,start:parseInt(fp.apply(void 0,e.map((function(e){return 63===e?48:e}))),16),end:parseInt(fp.apply(void 0,e.map((function(e){return 63===e?70:e}))),16)};var r=parseInt(fp.apply(void 0,e),16);if(45===this.peekCodePoint(0)&&df(this.peekCodePoint(1))){this.consumeCodePoint(),t=this.consumeCodePoint();for(var s=[];df(t)&&s.length<6;)s.push(t),t=this.consumeCodePoint();return{type:30,start:r,end:parseInt(fp.apply(void 0,s),16)}}return{type:30,start:r,end:r}},e.prototype.consumeIdentLikeToken=function(){var e=this.consumeName();return"url"===e.toLowerCase()&&40===this.peekCodePoint(0)?(this.consumeCodePoint(),this.consumeUrlToken()):40===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:19,value:e}):{type:20,value:e}},e.prototype.consumeUrlToken=function(){var e=[];if(this.consumeWhiteSpace(),-1===this.peekCodePoint(0))return{type:22,value:""};var t=this.peekCodePoint(0);if(39===t||34===t){var i=this.consumeStringToken(this.consumeCodePoint());return 0===i.type&&(this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0))?(this.consumeCodePoint(),{type:22,value:i.value}):(this.consumeBadUrlRemnants(),Sf)}for(;;){var r=this.consumeCodePoint();if(-1===r||41===r)return{type:22,value:fp.apply(void 0,e)};if(pf(r))return this.consumeWhiteSpace(),-1===this.peekCodePoint(0)||41===this.peekCodePoint(0)?(this.consumeCodePoint(),{type:22,value:fp.apply(void 0,e)}):(this.consumeBadUrlRemnants(),Sf);if(34===r||39===r||40===r||gf(r))return this.consumeBadUrlRemnants(),Sf;if(92===r){if(!mf(r,this.peekCodePoint(0)))return this.consumeBadUrlRemnants(),Sf;e.push(this.consumeEscapedCodePoint())}else e.push(r)}},e.prototype.consumeWhiteSpace=function(){for(;pf(this.peekCodePoint(0));)this.consumeCodePoint()},e.prototype.consumeBadUrlRemnants=function(){for(;;){var e=this.consumeCodePoint();if(41===e||-1===e)return;mf(e,this.peekCodePoint(0))&&this.consumeEscapedCodePoint()}},e.prototype.consumeStringSlice=function(e){for(var t="";e>0;){var i=Math.min(5e4,e);t+=fp.apply(void 0,this._value.splice(0,i)),e-=i}return this._value.shift(),t},e.prototype.consumeStringToken=function(e){for(var t="",i=0;;){var r=this._value[i];if(-1===r||void 0===r||r===e)return{type:0,value:t+=this.consumeStringSlice(i)};if(10===r)return this._value.splice(0,i),Tf;if(92===r){var s=this._value[i+1];-1!==s&&void 0!==s&&(10===s?(t+=this.consumeStringSlice(i),i=-1,this._value.shift()):mf(r,s)&&(t+=this.consumeStringSlice(i),t+=fp(this.consumeEscapedCodePoint()),i=-1))}i++}},e.prototype.consumeNumber=function(){var e=[],t=4,i=this.peekCodePoint(0);for(43!==i&&45!==i||e.push(this.consumeCodePoint());hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0);var r=this.peekCodePoint(1);if(46===i&&hf(r))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());i=this.peekCodePoint(0),r=this.peekCodePoint(1);var s=this.peekCodePoint(2);if((69===i||101===i)&&((43===r||45===r)&&hf(s)||hf(r)))for(e.push(this.consumeCodePoint(),this.consumeCodePoint()),t=8;hf(this.peekCodePoint(0));)e.push(this.consumeCodePoint());return[bf(e),t]},e.prototype.consumeNumericToken=function(){var e=this.consumeNumber(),t=e[0],i=e[1],r=this.peekCodePoint(0),s=this.peekCodePoint(1),n=this.peekCodePoint(2);return _f(r,s,n)?{type:15,number:t,flags:i,unit:this.consumeName()}:37===r?(this.consumeCodePoint(),{type:16,number:t,flags:i}):{type:17,number:t,flags:i}},e.prototype.consumeEscapedCodePoint=function(){var e=this.consumeCodePoint();if(df(e)){for(var t=fp(e);df(this.peekCodePoint(0))&&t.length<6;)t+=fp(this.consumeCodePoint());pf(this.peekCodePoint(0))&&this.consumeCodePoint();var i=parseInt(t,16);return 0===i||function(e){return e>=55296&&e<=57343}(i)||i>1114111?65533:i}return-1===e?65533:e},e.prototype.consumeName=function(){for(var e="";;){var t=this.consumeCodePoint();if(vf(t))e+=fp(t);else{if(!mf(t,this.peekCodePoint(0)))return this.reconsumeCodePoint(t),e;e+=fp(this.consumeEscapedCodePoint())}}},e}(),Gf=function(){function e(e){this._tokens=e}return e.create=function(t){var i=new jf;return i.write(t),new e(i.read())},e.parseValue=function(t){return e.create(t).parseComponentValue()},e.parseValues=function(t){return e.create(t).parseComponentValues()},e.prototype.parseComponentValue=function(){for(var e=this.consumeToken();31===e.type;)e=this.consumeToken();if(32===e.type)throw new SyntaxError("Error parsing CSS component value, unexpected EOF");this.reconsumeToken(e);var t=this.consumeComponentValue();do{e=this.consumeToken()}while(31===e.type);if(32===e.type)return t;throw new SyntaxError("Error parsing CSS component value, multiple values found when expecting only one")},e.prototype.parseComponentValues=function(){for(var e=[];;){var t=this.consumeComponentValue();if(32===t.type)return e;e.push(t),e.push()}},e.prototype.consumeComponentValue=function(){var e=this.consumeToken();switch(e.type){case 11:case 28:case 2:return this.consumeSimpleBlock(e.type);case 19:return this.consumeFunction(e)}return e},e.prototype.consumeSimpleBlock=function(e){for(var t={type:e,values:[]},i=this.consumeToken();;){if(32===i.type||$f(i,e))return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue()),i=this.consumeToken()}},e.prototype.consumeFunction=function(e){for(var t={name:e.value,values:[],type:18};;){var i=this.consumeToken();if(32===i.type||3===i.type)return t;this.reconsumeToken(i),t.values.push(this.consumeComponentValue())}},e.prototype.consumeToken=function(){var e=this._tokens.shift();return void 0===e?Hf:e},e.prototype.reconsumeToken=function(e){this._tokens.unshift(e)},e}(),zf=function(e){return 15===e.type},Wf=function(e){return 17===e.type},Kf=function(e){return 20===e.type},Xf=function(e){return 0===e.type},Yf=function(e,t){return Kf(e)&&e.value===t},Jf=function(e){return 31!==e.type},Zf=function(e){return 31!==e.type&&4!==e.type},qf=function(e){var t=[],i=[];return e.forEach((function(e){if(4===e.type){if(0===i.length)throw new Error("Error parsing function args, zero tokens for arg");return t.push(i),void(i=[])}31!==e.type&&i.push(e)})),i.length&&t.push(i),t},$f=function(e,t){return 11===t&&12===e.type||(28===t&&29===e.type||2===t&&3===e.type)},ev=function(e){return 17===e.type||15===e.type},tv=function(e){return 16===e.type||ev(e)},iv=function(e){return e.length>1?[e[0],e[1]]:[e[0]]},rv={type:17,number:0,flags:4},sv={type:16,number:50,flags:4},nv={type:16,number:100,flags:4},ov=function(e,t,i){var r=e[0],s=e[1];return[av(r,t),av(void 0!==s?s:r,i)]},av=function(e,t){if(16===e.type)return e.number/100*t;if(zf(e))switch(e.unit){case"rem":case"em":return 16*e.number;default:return e.number}return e.number},lv=function(e,t){if(15===t.type)switch(t.unit){case"deg":return Math.PI*t.number/180;case"grad":return Math.PI/200*t.number;case"rad":return t.number;case"turn":return 2*Math.PI*t.number}throw new Error("Unsupported angle type")},uv=function(e){return 15===e.type&&("deg"===e.unit||"grad"===e.unit||"rad"===e.unit||"turn"===e.unit)},Av=function(e){switch(e.filter(Kf).map((function(e){return e.value})).join(" ")){case"to bottom right":case"to right bottom":case"left top":case"top left":return[rv,rv];case"to top":case"bottom":return cv(0);case"to bottom left":case"to left bottom":case"right top":case"top right":return[rv,nv];case"to right":case"left":return cv(90);case"to top left":case"to left top":case"right bottom":case"bottom right":return[nv,nv];case"to bottom":case"top":return cv(180);case"to top right":case"to right top":case"left bottom":case"bottom left":return[nv,rv];case"to left":case"right":return cv(270)}return 0},cv=function(e){return Math.PI*e/180},hv=function(e,t){if(18===t.type){var i=yv[t.name];if(void 0===i)throw new Error('Attempting to parse an unsupported color function "'+t.name+'"');return i(e,t.values)}if(5===t.type){if(3===t.value.length){var r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);return fv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),1)}if(4===t.value.length){r=t.value.substring(0,1),s=t.value.substring(1,2),n=t.value.substring(2,3);var o=t.value.substring(3,4);return fv(parseInt(r+r,16),parseInt(s+s,16),parseInt(n+n,16),parseInt(o+o,16)/255)}if(6===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6);return fv(parseInt(r,16),parseInt(s,16),parseInt(n,16),1)}if(8===t.value.length){r=t.value.substring(0,2),s=t.value.substring(2,4),n=t.value.substring(4,6),o=t.value.substring(6,8);return fv(parseInt(r,16),parseInt(s,16),parseInt(n,16),parseInt(o,16)/255)}}if(20===t.type){var a=wv[t.value.toUpperCase()];if(void 0!==a)return a}return wv.TRANSPARENT},dv=function(e){return 0==(255&e)},pv=function(e){var t=255&e,i=255&e>>8,r=255&e>>16,s=255&e>>24;return t<255?"rgba("+s+","+r+","+i+","+t/255+")":"rgb("+s+","+r+","+i+")"},fv=function(e,t,i,r){return(e<<24|t<<16|i<<8|Math.round(255*r)<<0)>>>0},vv=function(e,t){if(17===e.type)return e.number;if(16===e.type){var i=3===t?1:255;return 3===t?e.number/100*i:Math.round(e.number/100*i)}return 0},gv=function(e,t){var i=t.filter(Zf);if(3===i.length){var r=i.map(vv),s=r[0],n=r[1],o=r[2];return fv(s,n,o,1)}if(4===i.length){var a=i.map(vv),l=(s=a[0],n=a[1],o=a[2],a[3]);return fv(s,n,o,l)}return 0};function mv(e,t,i){return i<0&&(i+=1),i>=1&&(i-=1),i<1/6?(t-e)*i*6+e:i<.5?t:i<2/3?6*(t-e)*(2/3-i)+e:e}var _v=function(e,t){var i=t.filter(Zf),r=i[0],s=i[1],n=i[2],o=i[3],a=(17===r.type?cv(r.number):lv(e,r))/(2*Math.PI),l=tv(s)?s.number/100:0,u=tv(n)?n.number/100:0,A=void 0!==o&&tv(o)?av(o,1):1;if(0===l)return fv(255*u,255*u,255*u,1);var c=u<=.5?u*(l+1):u+l-u*l,h=2*u-c,d=mv(h,c,a+1/3),p=mv(h,c,a),f=mv(h,c,a-1/3);return fv(255*d,255*p,255*f,A)},yv={hsl:_v,hsla:_v,rgb:gv,rgba:gv},bv=function(e,t){return hv(e,Gf.create(t).parseComponentValue())},wv={ALICEBLUE:4042850303,ANTIQUEWHITE:4209760255,AQUA:16777215,AQUAMARINE:2147472639,AZURE:4043309055,BEIGE:4126530815,BISQUE:4293182719,BLACK:255,BLANCHEDALMOND:4293643775,BLUE:65535,BLUEVIOLET:2318131967,BROWN:2771004159,BURLYWOOD:3736635391,CADETBLUE:1604231423,CHARTREUSE:2147418367,CHOCOLATE:3530104575,CORAL:4286533887,CORNFLOWERBLUE:1687547391,CORNSILK:4294499583,CRIMSON:3692313855,CYAN:16777215,DARKBLUE:35839,DARKCYAN:9145343,DARKGOLDENROD:3095837695,DARKGRAY:2846468607,DARKGREEN:6553855,DARKGREY:2846468607,DARKKHAKI:3182914559,DARKMAGENTA:2332068863,DARKOLIVEGREEN:1433087999,DARKORANGE:4287365375,DARKORCHID:2570243327,DARKRED:2332033279,DARKSALMON:3918953215,DARKSEAGREEN:2411499519,DARKSLATEBLUE:1211993087,DARKSLATEGRAY:793726975,DARKSLATEGREY:793726975,DARKTURQUOISE:13554175,DARKVIOLET:2483082239,DEEPPINK:4279538687,DEEPSKYBLUE:12582911,DIMGRAY:1768516095,DIMGREY:1768516095,DODGERBLUE:512819199,FIREBRICK:2988581631,FLORALWHITE:4294635775,FORESTGREEN:579543807,FUCHSIA:4278255615,GAINSBORO:3705462015,GHOSTWHITE:4177068031,GOLD:4292280575,GOLDENROD:3668254975,GRAY:2155905279,GREEN:8388863,GREENYELLOW:2919182335,GREY:2155905279,HONEYDEW:4043305215,HOTPINK:4285117695,INDIANRED:3445382399,INDIGO:1258324735,IVORY:4294963455,KHAKI:4041641215,LAVENDER:3873897215,LAVENDERBLUSH:4293981695,LAWNGREEN:2096890111,LEMONCHIFFON:4294626815,LIGHTBLUE:2916673279,LIGHTCORAL:4034953471,LIGHTCYAN:3774873599,LIGHTGOLDENRODYELLOW:4210742015,LIGHTGRAY:3553874943,LIGHTGREEN:2431553791,LIGHTGREY:3553874943,LIGHTPINK:4290167295,LIGHTSALMON:4288707327,LIGHTSEAGREEN:548580095,LIGHTSKYBLUE:2278488831,LIGHTSLATEGRAY:2005441023,LIGHTSLATEGREY:2005441023,LIGHTSTEELBLUE:2965692159,LIGHTYELLOW:4294959359,LIME:16711935,LIMEGREEN:852308735,LINEN:4210091775,MAGENTA:4278255615,MAROON:2147483903,MEDIUMAQUAMARINE:1724754687,MEDIUMBLUE:52735,MEDIUMORCHID:3126187007,MEDIUMPURPLE:2473647103,MEDIUMSEAGREEN:1018393087,MEDIUMSLATEBLUE:2070474495,MEDIUMSPRINGGREEN:16423679,MEDIUMTURQUOISE:1221709055,MEDIUMVIOLETRED:3340076543,MIDNIGHTBLUE:421097727,MINTCREAM:4127193855,MISTYROSE:4293190143,MOCCASIN:4293178879,NAVAJOWHITE:4292783615,NAVY:33023,OLDLACE:4260751103,OLIVE:2155872511,OLIVEDRAB:1804477439,ORANGE:4289003775,ORANGERED:4282712319,ORCHID:3664828159,PALEGOLDENROD:4008225535,PALEGREEN:2566625535,PALETURQUOISE:2951671551,PALEVIOLETRED:3681588223,PAPAYAWHIP:4293907967,PEACHPUFF:4292524543,PERU:3448061951,PINK:4290825215,PLUM:3718307327,POWDERBLUE:2967529215,PURPLE:2147516671,REBECCAPURPLE:1714657791,RED:4278190335,ROSYBROWN:3163525119,ROYALBLUE:1097458175,SADDLEBROWN:2336560127,SALMON:4202722047,SANDYBROWN:4104413439,SEAGREEN:780883967,SEASHELL:4294307583,SIENNA:2689740287,SILVER:3233857791,SKYBLUE:2278484991,SLATEBLUE:1784335871,SLATEGRAY:1887473919,SLATEGREY:1887473919,SNOW:4294638335,SPRINGGREEN:16744447,STEELBLUE:1182971135,TAN:3535047935,TEAL:8421631,THISTLE:3636451583,TOMATO:4284696575,TRANSPARENT:0,TURQUOISE:1088475391,VIOLET:4001558271,WHEAT:4125012991,WHITE:4294967295,WHITESMOKE:4126537215,YELLOW:4294902015,YELLOWGREEN:2597139199},Bv={name:"background-clip",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Kf(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},xv={name:"background-color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Pv=function(e,t){var i=hv(e,t[0]),r=t[1];return r&&tv(r)?{color:i,stop:r}:{color:i,stop:null}},Cv=function(e,t){var i=e[0],r=e[e.length-1];null===i.stop&&(i.stop=rv),null===r.stop&&(r.stop=nv);for(var s=[],n=0,o=0;on?s.push(l):s.push(n),n=l}else s.push(null)}var u=null;for(o=0;oe.optimumDistance)?{optimumCorner:t,optimumDistance:a}:e}),{optimumDistance:s?1/0:-1/0,optimumCorner:null}).optimumCorner},kv=function(e,t){var i=cv(180),r=[];return qf(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&-1!==["top","left","right","bottom"].indexOf(n.value))return void(i=Av(t));if(uv(n))return void(i=(lv(e,n)+cv(270))%cv(360))}var o=Pv(e,t);r.push(o)})),{angle:i,stops:r,type:1}},Iv=function(e,t){var i=0,r=3,s=[],n=[];return qf(t).forEach((function(t,o){var a=!0;if(0===o?a=t.reduce((function(e,t){if(Kf(t))switch(t.value){case"center":return n.push(sv),!1;case"top":case"left":return n.push(rv),!1;case"right":case"bottom":return n.push(nv),!1}else if(tv(t)||ev(t))return n.push(t),!1;return e}),a):1===o&&(a=t.reduce((function(e,t){if(Kf(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"contain":case"closest-side":return r=0,!1;case"farthest-side":return r=1,!1;case"closest-corner":return r=2,!1;case"cover":case"farthest-corner":return r=3,!1}else if(ev(t)||tv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)),a){var l=Pv(e,t);s.push(l)}})),{size:r,shape:i,stops:s,position:n,type:2}},Dv=function(e,t){if(22===t.type){var i={url:t.value,type:0};return e.cache.addImage(t.value),i}if(18===t.type){var r=Tv[t.name];if(void 0===r)throw new Error('Attempting to parse an unsupported image function "'+t.name+'"');return r(e,t.values)}throw new Error("Unsupported image type "+t.type)};var Sv,Tv={"linear-gradient":function(e,t){var i=cv(180),r=[];return qf(t).forEach((function(t,s){if(0===s){var n=t[0];if(20===n.type&&"to"===n.value)return void(i=Av(t));if(uv(n))return void(i=lv(e,n))}var o=Pv(e,t);r.push(o)})),{angle:i,stops:r,type:1}},"-moz-linear-gradient":kv,"-ms-linear-gradient":kv,"-o-linear-gradient":kv,"-webkit-linear-gradient":kv,"radial-gradient":function(e,t){var i=0,r=3,s=[],n=[];return qf(t).forEach((function(t,o){var a=!0;if(0===o){var l=!1;a=t.reduce((function(e,t){if(l)if(Kf(t))switch(t.value){case"center":return n.push(sv),e;case"top":case"left":return n.push(rv),e;case"right":case"bottom":return n.push(nv),e}else(tv(t)||ev(t))&&n.push(t);else if(Kf(t))switch(t.value){case"circle":return i=0,!1;case"ellipse":return i=1,!1;case"at":return l=!0,!1;case"closest-side":return r=0,!1;case"cover":case"farthest-side":return r=1,!1;case"contain":case"closest-corner":return r=2,!1;case"farthest-corner":return r=3,!1}else if(ev(t)||tv(t))return Array.isArray(r)||(r=[]),r.push(t),!1;return e}),a)}if(a){var u=Pv(e,t);s.push(u)}})),{size:r,shape:i,stops:s,position:n,type:2}},"-moz-radial-gradient":Iv,"-ms-radial-gradient":Iv,"-o-radial-gradient":Iv,"-webkit-radial-gradient":Iv,"-webkit-gradient":function(e,t){var i=cv(180),r=[],s=1;return qf(t).forEach((function(t,i){var n=t[0];if(0===i){if(Kf(n)&&"linear"===n.value)return void(s=1);if(Kf(n)&&"radial"===n.value)return void(s=2)}if(18===n.type)if("from"===n.name){var o=hv(e,n.values[0]);r.push({stop:rv,color:o})}else if("to"===n.name){o=hv(e,n.values[0]);r.push({stop:nv,color:o})}else if("color-stop"===n.name){var a=n.values.filter(Zf);if(2===a.length){o=hv(e,a[1]);var l=a[0];Wf(l)&&r.push({stop:{type:16,number:100*l.number,flags:l.flags},color:o})}}})),1===s?{angle:(i+cv(180))%cv(360),stops:r,type:s}:{size:3,shape:0,stops:r,position:[],type:s}}},Lv={name:"background-image",initialValue:"none",type:1,prefix:!1,parse:function(e,t){if(0===t.length)return[];var i=t[0];return 20===i.type&&"none"===i.value?[]:t.filter((function(e){return Zf(e)&&function(e){return!(20===e.type&&"none"===e.value||18===e.type&&!Tv[e.name])}(e)})).map((function(t){return Dv(e,t)}))}},Rv={name:"background-origin",initialValue:"border-box",prefix:!1,type:1,parse:function(e,t){return t.map((function(e){if(Kf(e))switch(e.value){case"padding-box":return 1;case"content-box":return 2}return 0}))}},Uv={name:"background-position",initialValue:"0% 0%",type:1,prefix:!1,parse:function(e,t){return qf(t).map((function(e){return e.filter(tv)})).map(iv)}},Ov={name:"background-repeat",initialValue:"repeat",prefix:!1,type:1,parse:function(e,t){return qf(t).map((function(e){return e.filter(Kf).map((function(e){return e.value})).join(" ")})).map(Nv)}},Nv=function(e){switch(e){case"no-repeat":return 1;case"repeat-x":case"repeat no-repeat":return 2;case"repeat-y":case"no-repeat repeat":return 3;default:return 0}};!function(e){e.AUTO="auto",e.CONTAIN="contain",e.COVER="cover"}(Sv||(Sv={}));var Qv,Vv={name:"background-size",initialValue:"0",prefix:!1,type:1,parse:function(e,t){return qf(t).map((function(e){return e.filter(Hv)}))}},Hv=function(e){return Kf(e)||tv(e)},jv=function(e){return{name:"border-"+e+"-color",initialValue:"transparent",prefix:!1,type:3,format:"color"}},Gv=jv("top"),zv=jv("right"),Wv=jv("bottom"),Kv=jv("left"),Xv=function(e){return{name:"border-radius-"+e,initialValue:"0 0",prefix:!1,type:1,parse:function(e,t){return iv(t.filter(tv))}}},Yv=Xv("top-left"),Jv=Xv("top-right"),Zv=Xv("bottom-right"),qv=Xv("bottom-left"),$v=function(e){return{name:"border-"+e+"-style",initialValue:"solid",prefix:!1,type:2,parse:function(e,t){switch(t){case"none":return 0;case"dashed":return 2;case"dotted":return 3;case"double":return 4}return 1}}},eg=$v("top"),tg=$v("right"),ig=$v("bottom"),rg=$v("left"),sg=function(e){return{name:"border-"+e+"-width",initialValue:"0",type:0,prefix:!1,parse:function(e,t){return zf(t)?t.number:0}}},ng=sg("top"),og=sg("right"),ag=sg("bottom"),lg=sg("left"),ug={name:"color",initialValue:"transparent",prefix:!1,type:3,format:"color"},Ag={name:"direction",initialValue:"ltr",prefix:!1,type:2,parse:function(e,t){return"rtl"===t?1:0}},cg={name:"display",initialValue:"inline-block",prefix:!1,type:1,parse:function(e,t){return t.filter(Kf).reduce((function(e,t){return e|hg(t.value)}),0)}},hg=function(e){switch(e){case"block":case"-webkit-box":return 2;case"inline":return 4;case"run-in":return 8;case"flow":return 16;case"flow-root":return 32;case"table":return 64;case"flex":case"-webkit-flex":return 128;case"grid":case"-ms-grid":return 256;case"ruby":return 512;case"subgrid":return 1024;case"list-item":return 2048;case"table-row-group":return 4096;case"table-header-group":return 8192;case"table-footer-group":return 16384;case"table-row":return 32768;case"table-cell":return 65536;case"table-column-group":return 131072;case"table-column":return 262144;case"table-caption":return 524288;case"ruby-base":return 1048576;case"ruby-text":return 2097152;case"ruby-base-container":return 4194304;case"ruby-text-container":return 8388608;case"contents":return 16777216;case"inline-block":return 33554432;case"inline-list-item":return 67108864;case"inline-table":return 134217728;case"inline-flex":return 268435456;case"inline-grid":return 536870912}return 0},dg={name:"float",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"left":return 1;case"right":return 2;case"inline-start":return 3;case"inline-end":return 4}return 0}},pg={name:"letter-spacing",initialValue:"0",prefix:!1,type:0,parse:function(e,t){return 20===t.type&&"normal"===t.value?0:17===t.type||15===t.type?t.number:0}};!function(e){e.NORMAL="normal",e.STRICT="strict"}(Qv||(Qv={}));var fg,vg={name:"line-break",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"strict"===t?Qv.STRICT:Qv.NORMAL}},gg={name:"line-height",initialValue:"normal",prefix:!1,type:4},mg=function(e,t){return Kf(e)&&"normal"===e.value?1.2*t:17===e.type?t*e.number:tv(e)?av(e,t):t},_g={name:"list-style-image",initialValue:"none",type:0,prefix:!1,parse:function(e,t){return 20===t.type&&"none"===t.value?null:Dv(e,t)}},yg={name:"list-style-position",initialValue:"outside",prefix:!1,type:2,parse:function(e,t){return"inside"===t?0:1}},bg={name:"list-style-type",initialValue:"none",prefix:!1,type:2,parse:function(e,t){switch(t){case"disc":return 0;case"circle":return 1;case"square":return 2;case"decimal":return 3;case"cjk-decimal":return 4;case"decimal-leading-zero":return 5;case"lower-roman":return 6;case"upper-roman":return 7;case"lower-greek":return 8;case"lower-alpha":return 9;case"upper-alpha":return 10;case"arabic-indic":return 11;case"armenian":return 12;case"bengali":return 13;case"cambodian":return 14;case"cjk-earthly-branch":return 15;case"cjk-heavenly-stem":return 16;case"cjk-ideographic":return 17;case"devanagari":return 18;case"ethiopic-numeric":return 19;case"georgian":return 20;case"gujarati":return 21;case"gurmukhi":case"hebrew":return 22;case"hiragana":return 23;case"hiragana-iroha":return 24;case"japanese-formal":return 25;case"japanese-informal":return 26;case"kannada":return 27;case"katakana":return 28;case"katakana-iroha":return 29;case"khmer":return 30;case"korean-hangul-formal":return 31;case"korean-hanja-formal":return 32;case"korean-hanja-informal":return 33;case"lao":return 34;case"lower-armenian":return 35;case"malayalam":return 36;case"mongolian":return 37;case"myanmar":return 38;case"oriya":return 39;case"persian":return 40;case"simp-chinese-formal":return 41;case"simp-chinese-informal":return 42;case"tamil":return 43;case"telugu":return 44;case"thai":return 45;case"tibetan":return 46;case"trad-chinese-formal":return 47;case"trad-chinese-informal":return 48;case"upper-armenian":return 49;case"disclosure-open":return 50;case"disclosure-closed":return 51;default:return-1}}},wg=function(e){return{name:"margin-"+e,initialValue:"0",prefix:!1,type:4}},Bg=wg("top"),xg=wg("right"),Pg=wg("bottom"),Cg=wg("left"),Mg={name:"overflow",initialValue:"visible",prefix:!1,type:1,parse:function(e,t){return t.filter(Kf).map((function(e){switch(e.value){case"hidden":return 1;case"scroll":return 2;case"clip":return 3;case"auto":return 4;default:return 0}}))}},Eg={name:"overflow-wrap",initialValue:"normal",prefix:!1,type:2,parse:function(e,t){return"break-word"===t?"break-word":"normal"}},Fg=function(e){return{name:"padding-"+e,initialValue:"0",prefix:!1,type:3,format:"length-percentage"}},kg=Fg("top"),Ig=Fg("right"),Dg=Fg("bottom"),Sg=Fg("left"),Tg={name:"text-align",initialValue:"left",prefix:!1,type:2,parse:function(e,t){switch(t){case"right":return 2;case"center":case"justify":return 1;default:return 0}}},Lg={name:"position",initialValue:"static",prefix:!1,type:2,parse:function(e,t){switch(t){case"relative":return 1;case"absolute":return 2;case"fixed":return 3;case"sticky":return 4}return 0}},Rg={name:"text-shadow",initialValue:"none",type:1,prefix:!1,parse:function(e,t){return 1===t.length&&Yf(t[0],"none")?[]:qf(t).map((function(t){for(var i={color:wv.TRANSPARENT,offsetX:rv,offsetY:rv,blur:rv},r=0,s=0;s1?1:0],this.overflowWrap=fm(e,Eg,t.overflowWrap),this.paddingTop=fm(e,kg,t.paddingTop),this.paddingRight=fm(e,Ig,t.paddingRight),this.paddingBottom=fm(e,Dg,t.paddingBottom),this.paddingLeft=fm(e,Sg,t.paddingLeft),this.paintOrder=fm(e,um,t.paintOrder),this.position=fm(e,Lg,t.position),this.textAlign=fm(e,Tg,t.textAlign),this.textDecorationColor=fm(e,Xg,null!==(i=t.textDecorationColor)&&void 0!==i?i:t.color),this.textDecorationLine=fm(e,Yg,null!==(r=t.textDecorationLine)&&void 0!==r?r:t.textDecoration),this.textShadow=fm(e,Rg,t.textShadow),this.textTransform=fm(e,Ug,t.textTransform),this.transform=fm(e,Og,t.transform),this.transformOrigin=fm(e,Hg,t.transformOrigin),this.visibility=fm(e,jg,t.visibility),this.webkitTextStrokeColor=fm(e,Am,t.webkitTextStrokeColor),this.webkitTextStrokeWidth=fm(e,cm,t.webkitTextStrokeWidth),this.wordBreak=fm(e,Gg,t.wordBreak),this.zIndex=fm(e,zg,t.zIndex)}return e.prototype.isVisible=function(){return this.display>0&&this.opacity>0&&0===this.visibility},e.prototype.isTransparent=function(){return dv(this.backgroundColor)},e.prototype.isTransformed=function(){return null!==this.transform},e.prototype.isPositioned=function(){return 0!==this.position},e.prototype.isPositionedWithZIndex=function(){return this.isPositioned()&&!this.zIndex.auto},e.prototype.isFloating=function(){return 0!==this.float},e.prototype.isInlineLevel=function(){return tm(this.display,4)||tm(this.display,33554432)||tm(this.display,268435456)||tm(this.display,536870912)||tm(this.display,67108864)||tm(this.display,134217728)},e}(),dm=function(e,t){this.content=fm(e,im,t.content),this.quotes=fm(e,om,t.quotes)},pm=function(e,t){this.counterIncrement=fm(e,rm,t.counterIncrement),this.counterReset=fm(e,sm,t.counterReset)},fm=function(e,t,i){var r=new jf,s=null!=i?i.toString():t.initialValue;r.write(s);var n=new Gf(r.read());switch(t.type){case 2:var o=n.parseComponentValue();return t.parse(e,Kf(o)?o.value:t.initialValue);case 0:return t.parse(e,n.parseComponentValue());case 1:return t.parse(e,n.parseComponentValues());case 4:return n.parseComponentValue();case 3:switch(t.format){case"angle":return lv(e,n.parseComponentValue());case"color":return hv(e,n.parseComponentValue());case"image":return Dv(e,n.parseComponentValue());case"length":var a=n.parseComponentValue();return ev(a)?a:rv;case"length-percentage":var l=n.parseComponentValue();return tv(l)?l:rv;case"time":return Wg(e,n.parseComponentValue())}}},vm=function(e,t){var i=function(e){switch(e.getAttribute("data-html2canvas-debug")){case"all":return 1;case"clone":return 2;case"parse":return 3;case"render":return 4;default:return 0}}(e);return 1===i||t===i},gm=function(e,t){this.context=e,this.textNodes=[],this.elements=[],this.flags=0,vm(t,3),this.styles=new hm(e,window.getComputedStyle(t,null)),g_(t)&&(this.styles.animationDuration.some((function(e){return e>0}))&&(t.style.animationDuration="0s"),null!==this.styles.transform&&(t.style.transform="none")),this.bounds=dp(this.context,t),vm(t,4)&&(this.flags|=16)},mm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_m="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ym=0;ym=0){if(e<55296||e>56319&&e<=65535)return t=((t=this.index[e>>5])<<2)+(31&e),this.data[t];if(e<=65535)return t=((t=this.index[2048+(e-55296>>5)])<<2)+(31&e),this.data[t];if(e>11),t=this.index[t],t+=e>>5&63,t=((t=this.index[t])<<2)+(31&e),this.data[t];if(e<=1114111)return this.data[this.highValueIndex]}return this.errorValue},e}(),Bm="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xm="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Pm=0;Pm>10),o%1024+56320)),(s+1===i||r.length>16384)&&(n+=String.fromCharCode.apply(String,r),r.length=0)}return n},Dm=function(e,t){var i,r,s,n=function(e){var t,i,r,s,n,o=.75*e.length,a=e.length,l=0;"="===e[e.length-1]&&(o--,"="===e[e.length-2]&&o--);var u="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&void 0!==Uint8Array.prototype.slice?new ArrayBuffer(o):new Array(o),A=Array.isArray(u)?u:new Uint8Array(u);for(t=0;t>4,A[l++]=(15&r)<<4|s>>2,A[l++]=(3&s)<<6|63&n;return u}(e),o=Array.isArray(n)?function(e){for(var t=e.length,i=[],r=0;r=55296&&s<=56319&&i=i)return{done:!0,value:null};for(var e="×";ro.x||s.y>o.y;return o=s,0===t||a}));return e.body.removeChild(t),a}(document);return Object.defineProperty(Nm,"SUPPORT_WORD_BREAKING",{value:e}),e},get SUPPORT_SVG_DRAWING(){var e=function(e){var t=new Image,i=e.createElement("canvas"),r=i.getContext("2d");if(!r)return!1;t.src="data:image/svg+xml,";try{r.drawImage(t,0,0),i.toDataURL()}catch(e){return!1}return!0}(document);return Object.defineProperty(Nm,"SUPPORT_SVG_DRAWING",{value:e}),e},get SUPPORT_FOREIGNOBJECT_DRAWING(){var e="function"==typeof Array.from&&"function"==typeof window.fetch?function(e){var t=e.createElement("canvas"),i=100;t.width=i,t.height=i;var r=t.getContext("2d");if(!r)return Promise.reject(!1);r.fillStyle="rgb(0, 255, 0)",r.fillRect(0,0,i,i);var s=new Image,n=t.toDataURL();s.src=n;var o=Um(i,i,0,0,s);return r.fillStyle="red",r.fillRect(0,0,i,i),Om(o).then((function(t){r.drawImage(t,0,0);var s=r.getImageData(0,0,i,i).data;r.fillStyle="red",r.fillRect(0,0,i,i);var o=e.createElement("div");return o.style.backgroundImage="url("+n+")",o.style.height="100px",Rm(s)?Om(Um(i,i,0,0,o)):Promise.reject(!1)})).then((function(e){return r.drawImage(e,0,0),Rm(r.getImageData(0,0,i,i).data)})).catch((function(){return!1}))}(document):Promise.resolve(!1);return Object.defineProperty(Nm,"SUPPORT_FOREIGNOBJECT_DRAWING",{value:e}),e},get SUPPORT_CORS_IMAGES(){var e=void 0!==(new Image).crossOrigin;return Object.defineProperty(Nm,"SUPPORT_CORS_IMAGES",{value:e}),e},get SUPPORT_RESPONSE_TYPE(){var e="string"==typeof(new XMLHttpRequest).responseType;return Object.defineProperty(Nm,"SUPPORT_RESPONSE_TYPE",{value:e}),e},get SUPPORT_CORS_XHR(){var e="withCredentials"in new XMLHttpRequest;return Object.defineProperty(Nm,"SUPPORT_CORS_XHR",{value:e}),e},get SUPPORT_NATIVE_TEXT_SEGMENTATION(){var e=!("undefined"==typeof Intl||!Intl.Segmenter);return Object.defineProperty(Nm,"SUPPORT_NATIVE_TEXT_SEGMENTATION",{value:e}),e}},Qm=function(e,t){this.text=e,this.bounds=t},Vm=function(e,t){var i=t.ownerDocument;if(i){var r=i.createElement("html2canvaswrapper");r.appendChild(t.cloneNode(!0));var s=t.parentNode;if(s){s.replaceChild(r,t);var n=dp(e,r);return r.firstChild&&s.replaceChild(r.firstChild,r),n}}return hp.EMPTY},Hm=function(e,t,i){var r=e.ownerDocument;if(!r)throw new Error("Node has no owner document");var s=r.createRange();return s.setStart(e,t),s.setEnd(e,t+i),s},jm=function(e){if(Nm.SUPPORT_NATIVE_TEXT_SEGMENTATION){var t=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(t.segment(e)).map((function(e){return e.segment}))}return function(e){for(var t,i=Lm(e),r=[];!(t=i.next()).done;)t.value&&r.push(t.value.slice());return r}(e)},Gm=function(e,t){return 0!==t.letterSpacing?jm(e):function(e,t){if(Nm.SUPPORT_NATIVE_TEXT_SEGMENTATION){var i=new Intl.Segmenter(void 0,{granularity:"word"});return Array.from(i.segment(e)).map((function(e){return e.segment}))}return Wm(e,t)}(e,t)},zm=[32,160,4961,65792,65793,4153,4241],Wm=function(e,t){for(var i,r=function(e,t){var i=pp(e),r=Af(i,t),s=r[0],n=r[1],o=r[2],a=i.length,l=0,u=0;return{next:function(){if(u>=a)return{done:!0,value:null};for(var e="×";u0)if(Nm.SUPPORT_RANGE_BOUNDS){var s=Hm(r,o,t.length).getClientRects();if(s.length>1){var a=jm(t),l=0;a.forEach((function(t){n.push(new Qm(t,hp.fromDOMRectList(e,Hm(r,l+o,t.length).getClientRects()))),l+=t.length}))}else n.push(new Qm(t,hp.fromDOMRectList(e,s)))}else{var u=r.splitText(t.length);n.push(new Qm(t,Vm(e,r))),r=u}else Nm.SUPPORT_RANGE_BOUNDS||(r=r.splitText(t.length));o+=t.length})),n}(e,this.text,i,t)},Xm=function(e,t){switch(t){case 1:return e.toLowerCase();case 3:return e.replace(Ym,Jm);case 2:return e.toUpperCase();default:return e}},Ym=/(^|\s|:|-|\(|\))([a-z])/g,Jm=function(e,t,i){return e.length>0?t+i.toUpperCase():e},Zm=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.src=i.currentSrc||i.src,r.intrinsicWidth=i.naturalWidth,r.intrinsicHeight=i.naturalHeight,r.context.cache.addImage(r.src),r}return ap(t,e),t}(gm),qm=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.canvas=i,r.intrinsicWidth=i.width,r.intrinsicHeight=i.height,r}return ap(t,e),t}(gm),$m=function(e){function t(t,i){var r=e.call(this,t,i)||this,s=new XMLSerializer,n=dp(t,i);return i.setAttribute("width",n.width+"px"),i.setAttribute("height",n.height+"px"),r.svg="data:image/svg+xml,"+encodeURIComponent(s.serializeToString(i)),r.intrinsicWidth=i.width.baseVal.value,r.intrinsicHeight=i.height.baseVal.value,r.context.cache.addImage(r.svg),r}return ap(t,e),t}(gm),e_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.value=i.value,r}return ap(t,e),t}(gm),t_=function(e){function t(t,i){var r=e.call(this,t,i)||this;return r.start=i.start,r.reversed="boolean"==typeof i.reversed&&!0===i.reversed,r}return ap(t,e),t}(gm),i_=[{type:15,flags:0,unit:"px",number:3}],r_=[{type:16,flags:0,number:50}],s_="password",n_=function(e){function t(t,i){var r,s=e.call(this,t,i)||this;switch(s.type=i.type.toLowerCase(),s.checked=i.checked,s.value=function(e){var t=e.type===s_?new Array(e.value.length+1).join("•"):e.value;return 0===t.length?e.placeholder||"":t}(i),"checkbox"!==s.type&&"radio"!==s.type||(s.styles.backgroundColor=3739148031,s.styles.borderTopColor=s.styles.borderRightColor=s.styles.borderBottomColor=s.styles.borderLeftColor=2779096575,s.styles.borderTopWidth=s.styles.borderRightWidth=s.styles.borderBottomWidth=s.styles.borderLeftWidth=1,s.styles.borderTopStyle=s.styles.borderRightStyle=s.styles.borderBottomStyle=s.styles.borderLeftStyle=1,s.styles.backgroundClip=[0],s.styles.backgroundOrigin=[0],s.bounds=(r=s.bounds).width>r.height?new hp(r.left+(r.width-r.height)/2,r.top,r.height,r.height):r.width0)r.textNodes.push(new Km(t,n,r.styles));else if(v_(n))if(I_(n)&&n.assignedNodes)n.assignedNodes().forEach((function(i){return e(t,i,r,s)}));else{var a=c_(t,n);a.styles.isVisible()&&(d_(n,a,s)?a.flags|=4:p_(a.styles)&&(a.flags|=2),-1!==u_.indexOf(n.tagName)&&(a.flags|=8),r.elements.push(a),n.slot,n.shadowRoot?e(t,n.shadowRoot,a,s):F_(n)||w_(n)||k_(n)||e(t,n,a,s))}},c_=function(e,t){return C_(t)?new Zm(e,t):x_(t)?new qm(e,t):w_(t)?new $m(e,t):__(t)?new e_(e,t):y_(t)?new t_(e,t):b_(t)?new n_(e,t):k_(t)?new o_(e,t):F_(t)?new a_(e,t):M_(t)?new l_(e,t):new gm(e,t)},h_=function(e,t){var i=c_(e,t);return i.flags|=4,A_(e,t,i,i),i},d_=function(e,t,i){return t.styles.isPositionedWithZIndex()||t.styles.opacity<1||t.styles.isTransformed()||B_(e)&&i.styles.isTransparent()},p_=function(e){return e.isPositioned()||e.isFloating()},f_=function(e){return e.nodeType===Node.TEXT_NODE},v_=function(e){return e.nodeType===Node.ELEMENT_NODE},g_=function(e){return v_(e)&&void 0!==e.style&&!m_(e)},m_=function(e){return"object"===B(e.className)},__=function(e){return"LI"===e.tagName},y_=function(e){return"OL"===e.tagName},b_=function(e){return"INPUT"===e.tagName},w_=function(e){return"svg"===e.tagName},B_=function(e){return"BODY"===e.tagName},x_=function(e){return"CANVAS"===e.tagName},P_=function(e){return"VIDEO"===e.tagName},C_=function(e){return"IMG"===e.tagName},M_=function(e){return"IFRAME"===e.tagName},E_=function(e){return"STYLE"===e.tagName},F_=function(e){return"TEXTAREA"===e.tagName},k_=function(e){return"SELECT"===e.tagName},I_=function(e){return"SLOT"===e.tagName},D_=function(e){return e.tagName.indexOf("-")>0},S_=function(){function e(){this.counters={}}return e.prototype.getCounterValue=function(e){var t=this.counters[e];return t&&t.length?t[t.length-1]:1},e.prototype.getCounterValues=function(e){var t=this.counters[e];return t||[]},e.prototype.pop=function(e){var t=this;e.forEach((function(e){return t.counters[e].pop()}))},e.prototype.parse=function(e){var t=this,i=e.counterIncrement,r=e.counterReset,s=!0;null!==i&&i.forEach((function(e){var i=t.counters[e.counter];i&&0!==e.increment&&(s=!1,i.length||i.push(1),i[Math.max(0,i.length-1)]+=e.increment)}));var n=[];return s&&r.forEach((function(e){var i=t.counters[e.counter];n.push(e.counter),i||(i=t.counters[e.counter]=[]),i.push(e.reset)})),n},e}(),T_={integers:[1e3,900,500,400,100,90,50,40,10,9,5,4,1],values:["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]},L_={integers:[9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["Ք","Փ","Ւ","Ց","Ր","Տ","Վ","Ս","Ռ","Ջ","Պ","Չ","Ո","Շ","Ն","Յ","Մ","Ճ","Ղ","Ձ","Հ","Կ","Ծ","Խ","Լ","Ի","Ժ","Թ","Ը","Է","Զ","Ե","Դ","Գ","Բ","Ա"]},R_={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,400,300,200,100,90,80,70,60,50,40,30,20,19,18,17,16,15,10,9,8,7,6,5,4,3,2,1],values:["י׳","ט׳","ח׳","ז׳","ו׳","ה׳","ד׳","ג׳","ב׳","א׳","ת","ש","ר","ק","צ","פ","ע","ס","נ","מ","ל","כ","יט","יח","יז","טז","טו","י","ט","ח","ז","ו","ה","ד","ג","ב","א"]},U_={integers:[1e4,9e3,8e3,7e3,6e3,5e3,4e3,3e3,2e3,1e3,900,800,700,600,500,400,300,200,100,90,80,70,60,50,40,30,20,10,9,8,7,6,5,4,3,2,1],values:["ჵ","ჰ","ჯ","ჴ","ხ","ჭ","წ","ძ","ც","ჩ","შ","ყ","ღ","ქ","ფ","ჳ","ტ","ს","რ","ჟ","პ","ო","ჲ","ნ","მ","ლ","კ","ი","თ","ჱ","ზ","ვ","ე","დ","გ","ბ","ა"]},O_=function(e,t,i,r,s,n){return ei?j_(e,s,n.length>0):r.integers.reduce((function(t,i,s){for(;e>=i;)e-=i,t+=r.values[s];return t}),"")+n},N_=function(e,t,i,r){var s="";do{i||e--,s=r(e)+s,e/=t}while(e*t>=t);return s},Q_=function(e,t,i,r,s){var n=i-t+1;return(e<0?"-":"")+(N_(Math.abs(e),n,r,(function(e){return fp(Math.floor(e%n)+t)}))+s)},V_=function(e,t,i){void 0===i&&(i=". ");var r=t.length;return N_(Math.abs(e),r,!1,(function(e){return t[Math.floor(e%r)]}))+i},H_=function(e,t,i,r,s,n){if(e<-9999||e>9999)return j_(e,4,s.length>0);var o=Math.abs(e),a=s;if(0===o)return t[0]+a;for(var l=0;o>0&&l<=4;l++){var u=o%10;0===u&&tm(n,1)&&""!==a?a=t[u]+a:u>1||1===u&&0===l||1===u&&1===l&&tm(n,2)||1===u&&1===l&&tm(n,4)&&e>100||1===u&&l>1&&tm(n,8)?a=t[u]+(l>0?i[l-1]:"")+a:1===u&&l>0&&(a=i[l-1]+a),o=Math.floor(o/10)}return(e<0?r:"")+a},j_=function(e,t,i){var r=i?". ":"",s=i?"、":"",n=i?", ":"",o=i?" ":"";switch(t){case 0:return"•"+o;case 1:return"◦"+o;case 2:return"◾"+o;case 5:var a=Q_(e,48,57,!0,r);return a.length<4?"0"+a:a;case 4:return V_(e,"〇一二三四五六七八九",s);case 6:return O_(e,1,3999,T_,3,r).toLowerCase();case 7:return O_(e,1,3999,T_,3,r);case 8:return Q_(e,945,969,!1,r);case 9:return Q_(e,97,122,!1,r);case 10:return Q_(e,65,90,!1,r);case 11:return Q_(e,1632,1641,!0,r);case 12:case 49:return O_(e,1,9999,L_,3,r);case 35:return O_(e,1,9999,L_,3,r).toLowerCase();case 13:return Q_(e,2534,2543,!0,r);case 14:case 30:return Q_(e,6112,6121,!0,r);case 15:return V_(e,"子丑寅卯辰巳午未申酉戌亥",s);case 16:return V_(e,"甲乙丙丁戊己庚辛壬癸",s);case 17:case 48:return H_(e,"零一二三四五六七八九","十百千萬","負",s,14);case 47:return H_(e,"零壹貳參肆伍陸柒捌玖","拾佰仟萬","負",s,15);case 42:return H_(e,"零一二三四五六七八九","十百千萬","负",s,14);case 41:return H_(e,"零壹贰叁肆伍陆柒捌玖","拾佰仟萬","负",s,15);case 26:return H_(e,"〇一二三四五六七八九","十百千万","マイナス",s,0);case 25:return H_(e,"零壱弐参四伍六七八九","拾百千万","マイナス",s,7);case 31:return H_(e,"영일이삼사오육칠팔구","십백천만","마이너스",n,7);case 33:return H_(e,"零一二三四五六七八九","十百千萬","마이너스",n,0);case 32:return H_(e,"零壹貳參四五六七八九","拾百千","마이너스",n,7);case 18:return Q_(e,2406,2415,!0,r);case 20:return O_(e,1,19999,U_,3,r);case 21:return Q_(e,2790,2799,!0,r);case 22:return Q_(e,2662,2671,!0,r);case 22:return O_(e,1,10999,R_,3,r);case 23:return V_(e,"あいうえおかきくけこさしすせそたちつてとなにぬねのはひふへほまみむめもやゆよらりるれろわゐゑをん");case 24:return V_(e,"いろはにほへとちりぬるをわかよたれそつねならむうゐのおくやまけふこえてあさきゆめみしゑひもせす");case 27:return Q_(e,3302,3311,!0,r);case 28:return V_(e,"アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン",s);case 29:return V_(e,"イロハニホヘトチリヌルヲワカヨタレソツネナラムウヰノオクヤマケフコエテアサキユメミシヱヒモセス",s);case 34:return Q_(e,3792,3801,!0,r);case 37:return Q_(e,6160,6169,!0,r);case 38:return Q_(e,4160,4169,!0,r);case 39:return Q_(e,2918,2927,!0,r);case 40:return Q_(e,1776,1785,!0,r);case 43:return Q_(e,3046,3055,!0,r);case 44:return Q_(e,3174,3183,!0,r);case 45:return Q_(e,3664,3673,!0,r);case 46:return Q_(e,3872,3881,!0,r);default:return Q_(e,48,57,!0,r)}},G_=function(){function e(e,t,i){if(this.context=e,this.options=i,this.scrolledElements=[],this.referenceElement=t,this.counters=new S_,this.quoteDepth=0,!t.ownerDocument)throw new Error("Cloned element does not have an owner document");this.documentElement=this.cloneNode(t.ownerDocument.documentElement,!1)}return e.prototype.toIFrame=function(e,t){var i=this,r=W_(e,t);if(!r.contentWindow)return Promise.reject("Unable to find iframe window");var s=e.defaultView.pageXOffset,n=e.defaultView.pageYOffset,o=r.contentWindow,a=o.document,l=Y_(r).then((function(){return up(i,void 0,void 0,(function(){var e,i;return Ap(this,(function(s){switch(s.label){case 0:return this.scrolledElements.forEach(ey),o&&(o.scrollTo(t.left,t.top),!/(iPad|iPhone|iPod)/g.test(navigator.userAgent)||o.scrollY===t.top&&o.scrollX===t.left||(this.context.logger.warn("Unable to restore scroll position for cloned document"),this.context.windowBounds=this.context.windowBounds.add(o.scrollX-t.left,o.scrollY-t.top,0,0))),e=this.options.onclone,void 0===(i=this.clonedReferenceElement)?[2,Promise.reject("Error finding the "+this.referenceElement.nodeName+" in the cloned document")]:a.fonts&&a.fonts.ready?[4,a.fonts.ready]:[3,2];case 1:s.sent(),s.label=2;case 2:return/(AppleWebKit)/g.test(navigator.userAgent)?[4,X_(a)]:[3,4];case 3:s.sent(),s.label=4;case 4:return"function"==typeof e?[2,Promise.resolve().then((function(){return e(a,i)})).then((function(){return r}))]:[2,r]}}))}))}));return a.open(),a.write(q_(document.doctype)+""),$_(this.referenceElement.ownerDocument,s,n),a.replaceChild(a.adoptNode(this.documentElement),a.documentElement),a.close(),l},e.prototype.createElementClone=function(e){if(vm(e,2),x_(e))return this.createCanvasClone(e);if(P_(e))return this.createVideoClone(e);if(E_(e))return this.createStyleClone(e);var t=e.cloneNode(!1);return C_(t)&&(C_(e)&&e.currentSrc&&e.currentSrc!==e.src&&(t.src=e.currentSrc,t.srcset=""),"lazy"===t.loading&&(t.loading="eager")),D_(t)?this.createCustomElementClone(t):t},e.prototype.createCustomElementClone=function(e){var t=document.createElement("html2canvascustomelement");return Z_(e.style,t),t},e.prototype.createStyleClone=function(e){try{var t=e.sheet;if(t&&t.cssRules){var i=[].slice.call(t.cssRules,0).reduce((function(e,t){return t&&"string"==typeof t.cssText?e+t.cssText:e}),""),r=e.cloneNode(!1);return r.textContent=i,r}}catch(e){if(this.context.logger.error("Unable to access cssRules property",e),"SecurityError"!==e.name)throw e}return e.cloneNode(!1)},e.prototype.createCanvasClone=function(e){var t;if(this.options.inlineImages&&e.ownerDocument){var i=e.ownerDocument.createElement("img");try{return i.src=e.toDataURL(),i}catch(t){this.context.logger.info("Unable to inline canvas contents, canvas is tainted",e)}}var r=e.cloneNode(!1);try{r.width=e.width,r.height=e.height;var s=e.getContext("2d"),n=r.getContext("2d");if(n)if(!this.options.allowTaint&&s)n.putImageData(s.getImageData(0,0,e.width,e.height),0,0);else{var o=null!==(t=e.getContext("webgl2"))&&void 0!==t?t:e.getContext("webgl");if(o){var a=o.getContextAttributes();!1===(null==a?void 0:a.preserveDrawingBuffer)&&this.context.logger.warn("Unable to clone WebGL context as it has preserveDrawingBuffer=false",e)}n.drawImage(e,0,0)}return r}catch(t){this.context.logger.info("Unable to clone canvas as it is tainted",e)}return r},e.prototype.createVideoClone=function(e){var t=e.ownerDocument.createElement("canvas");t.width=e.offsetWidth,t.height=e.offsetHeight;var i=t.getContext("2d");try{return i&&(i.drawImage(e,0,0,t.width,t.height),this.options.allowTaint||i.getImageData(0,0,t.width,t.height)),t}catch(t){this.context.logger.info("Unable to clone video as it is tainted",e)}var r=e.ownerDocument.createElement("canvas");return r.width=e.offsetWidth,r.height=e.offsetHeight,r},e.prototype.appendChildNode=function(e,t,i){v_(t)&&(function(e){return"SCRIPT"===e.tagName}(t)||t.hasAttribute("data-html2canvas-ignore")||"function"==typeof this.options.ignoreElements&&this.options.ignoreElements(t))||this.options.copyStyles&&v_(t)&&E_(t)||e.appendChild(this.cloneNode(t,i))},e.prototype.cloneChildNodes=function(e,t,i){for(var r=this,s=e.shadowRoot?e.shadowRoot.firstChild:e.firstChild;s;s=s.nextSibling)if(v_(s)&&I_(s)&&"function"==typeof s.assignedNodes){var n=s.assignedNodes();n.length&&n.forEach((function(e){return r.appendChildNode(t,e,i)}))}else this.appendChildNode(t,s,i)},e.prototype.cloneNode=function(e,t){if(f_(e))return document.createTextNode(e.data);if(!e.ownerDocument)return e.cloneNode(!1);var i=e.ownerDocument.defaultView;if(i&&v_(e)&&(g_(e)||m_(e))){var r=this.createElementClone(e);r.style.transitionProperty="none";var s=i.getComputedStyle(e),n=i.getComputedStyle(e,":before"),o=i.getComputedStyle(e,":after");this.referenceElement===e&&g_(r)&&(this.clonedReferenceElement=r),B_(r)&&ry(r);var a=this.counters.parse(new pm(this.context,s)),l=this.resolvePseudoContent(e,r,n,Cm.BEFORE);D_(e)&&(t=!0),P_(e)||this.cloneChildNodes(e,r,t),l&&r.insertBefore(l,r.firstChild);var u=this.resolvePseudoContent(e,r,o,Cm.AFTER);return u&&r.appendChild(u),this.counters.pop(a),(s&&(this.options.copyStyles||m_(e))&&!M_(e)||t)&&Z_(s,r),0===e.scrollTop&&0===e.scrollLeft||this.scrolledElements.push([r,e.scrollLeft,e.scrollTop]),(F_(e)||k_(e))&&(F_(r)||k_(r))&&(r.value=e.value),r}return e.cloneNode(!1)},e.prototype.resolvePseudoContent=function(e,t,i,r){var s=this;if(i){var n=i.content,o=t.ownerDocument;if(o&&n&&"none"!==n&&"-moz-alt-content"!==n&&"none"!==i.display){this.counters.parse(new pm(this.context,i));var a=new dm(this.context,i),l=o.createElement("html2canvaspseudoelement");Z_(i,l),a.content.forEach((function(t){if(0===t.type)l.appendChild(o.createTextNode(t.value));else if(22===t.type){var i=o.createElement("img");i.src=t.value,i.style.opacity="1",l.appendChild(i)}else if(18===t.type){if("attr"===t.name){var r=t.values.filter(Kf);r.length&&l.appendChild(o.createTextNode(e.getAttribute(r[0].value)||""))}else if("counter"===t.name){var n=t.values.filter(Zf),u=n[0],A=n[1];if(u&&Kf(u)){var c=s.counters.getCounterValue(u.value),h=A&&Kf(A)?bg.parse(s.context,A.value):3;l.appendChild(o.createTextNode(j_(c,h,!1)))}}else if("counters"===t.name){var d=t.values.filter(Zf),p=(u=d[0],d[1]);A=d[2];if(u&&Kf(u)){var f=s.counters.getCounterValues(u.value),v=A&&Kf(A)?bg.parse(s.context,A.value):3,g=p&&0===p.type?p.value:"",m=f.map((function(e){return j_(e,v,!1)})).join(g);l.appendChild(o.createTextNode(m))}}}else if(20===t.type)switch(t.value){case"open-quote":l.appendChild(o.createTextNode(am(a.quotes,s.quoteDepth++,!0)));break;case"close-quote":l.appendChild(o.createTextNode(am(a.quotes,--s.quoteDepth,!1)));break;default:l.appendChild(o.createTextNode(t.value))}})),l.className=ty+" "+iy;var u=r===Cm.BEFORE?" "+ty:" "+iy;return m_(t)?t.className.baseValue+=u:t.className+=u,l}}},e.destroy=function(e){return!!e.parentNode&&(e.parentNode.removeChild(e),!0)},e}();!function(e){e[e.BEFORE=0]="BEFORE",e[e.AFTER=1]="AFTER"}(Cm||(Cm={}));var z_,W_=function(e,t){var i=e.createElement("iframe");return i.className="html2canvas-container",i.style.visibility="hidden",i.style.position="fixed",i.style.left="-10000px",i.style.top="0px",i.style.border="0",i.width=t.width.toString(),i.height=t.height.toString(),i.scrolling="no",i.setAttribute("data-html2canvas-ignore","true"),e.body.appendChild(i),i},K_=function(e){return new Promise((function(t){e.complete?t():e.src?(e.onload=t,e.onerror=t):t()}))},X_=function(e){return Promise.all([].slice.call(e.images,0).map(K_))},Y_=function(e){return new Promise((function(t,i){var r=e.contentWindow;if(!r)return i("No window assigned for iframe");var s=r.document;r.onload=e.onload=function(){r.onload=e.onload=null;var i=setInterval((function(){s.body.childNodes.length>0&&"complete"===s.readyState&&(clearInterval(i),t(e))}),50)}}))},J_=["all","d","content"],Z_=function(e,t){for(var i=e.length-1;i>=0;i--){var r=e.item(i);-1===J_.indexOf(r)&&t.style.setProperty(r,e.getPropertyValue(r))}return t},q_=function(e){var t="";return e&&(t+=""),t},$_=function(e,t,i){e&&e.defaultView&&(t!==e.defaultView.pageXOffset||i!==e.defaultView.pageYOffset)&&e.defaultView.scrollTo(t,i)},ey=function(e){var t=e[0],i=e[1],r=e[2];t.scrollLeft=i,t.scrollTop=r},ty="___html2canvas___pseudoelement_before",iy="___html2canvas___pseudoelement_after",ry=function(e){sy(e,"."+ty+':before{\n content: "" !important;\n display: none !important;\n}\n .'+iy+':after{\n content: "" !important;\n display: none !important;\n}')},sy=function(e,t){var i=e.ownerDocument;if(i){var r=i.createElement("style");r.textContent=t,e.appendChild(r)}},ny=function(){function e(){}return e.getOrigin=function(t){var i=e._link;return i?(i.href=t,i.href=i.href,i.protocol+i.hostname+i.port):"about:blank"},e.isSameOrigin=function(t){return e.getOrigin(t)===e._origin},e.setContext=function(t){e._link=t.document.createElement("a"),e._origin=e.getOrigin(t.location.href)},e._origin="about:blank",e}(),oy=function(){function e(e,t){this.context=e,this._options=t,this._cache={}}return e.prototype.addImage=function(e){var t=Promise.resolve();return this.has(e)?t:dy(e)||Ay(e)?((this._cache[e]=this.loadImage(e)).catch((function(){})),t):t},e.prototype.match=function(e){return this._cache[e]},e.prototype.loadImage=function(e){return up(this,void 0,void 0,(function(){var t,i,r,s,n=this;return Ap(this,(function(o){switch(o.label){case 0:return t=ny.isSameOrigin(e),i=!cy(e)&&!0===this._options.useCORS&&Nm.SUPPORT_CORS_IMAGES&&!t,r=!cy(e)&&!t&&!dy(e)&&"string"==typeof this._options.proxy&&Nm.SUPPORT_CORS_XHR&&!i,t||!1!==this._options.allowTaint||cy(e)||dy(e)||r||i?(s=e,r?[4,this.proxy(s)]:[3,2]):[2];case 1:s=o.sent(),o.label=2;case 2:return this.context.logger.debug("Added image "+e.substring(0,256)),[4,new Promise((function(e,t){var r=new Image;r.onload=function(){return e(r)},r.onerror=t,(hy(s)||i)&&(r.crossOrigin="anonymous"),r.src=s,!0===r.complete&&setTimeout((function(){return e(r)}),500),n._options.imageTimeout>0&&setTimeout((function(){return t("Timed out ("+n._options.imageTimeout+"ms) loading image")}),n._options.imageTimeout)}))];case 3:return[2,o.sent()]}}))}))},e.prototype.has=function(e){return void 0!==this._cache[e]},e.prototype.keys=function(){return Promise.resolve(Object.keys(this._cache))},e.prototype.proxy=function(e){var t=this,i=this._options.proxy;if(!i)throw new Error("No proxy defined");var r=e.substring(0,256);return new Promise((function(s,n){var o=Nm.SUPPORT_RESPONSE_TYPE?"blob":"text",a=new XMLHttpRequest;a.onload=function(){if(200===a.status)if("text"===o)s(a.response);else{var e=new FileReader;e.addEventListener("load",(function(){return s(e.result)}),!1),e.addEventListener("error",(function(e){return n(e)}),!1),e.readAsDataURL(a.response)}else n("Failed to proxy resource "+r+" with status code "+a.status)},a.onerror=n;var l=i.indexOf("?")>-1?"&":"?";if(a.open("GET",""+i+l+"url="+encodeURIComponent(e)+"&responseType="+o),"text"!==o&&a instanceof XMLHttpRequest&&(a.responseType=o),t._options.imageTimeout){var u=t._options.imageTimeout;a.timeout=u,a.ontimeout=function(){return n("Timed out ("+u+"ms) proxying "+r)}}a.send()}))},e}(),ay=/^data:image\/svg\+xml/i,ly=/^data:image\/.*;base64,/i,uy=/^data:image\/.*/i,Ay=function(e){return Nm.SUPPORT_SVG_DRAWING||!py(e)},cy=function(e){return uy.test(e)},hy=function(e){return ly.test(e)},dy=function(e){return"blob"===e.substr(0,4)},py=function(e){return"svg"===e.substr(-3).toLowerCase()||ay.test(e)},fy=function(){function e(e,t){this.type=0,this.x=e,this.y=t}return e.prototype.add=function(t,i){return new e(this.x+t,this.y+i)},e}(),vy=function(e,t,i){return new fy(e.x+(t.x-e.x)*i,e.y+(t.y-e.y)*i)},gy=function(){function e(e,t,i,r){this.type=1,this.start=e,this.startControl=t,this.endControl=i,this.end=r}return e.prototype.subdivide=function(t,i){var r=vy(this.start,this.startControl,t),s=vy(this.startControl,this.endControl,t),n=vy(this.endControl,this.end,t),o=vy(r,s,t),a=vy(s,n,t),l=vy(o,a,t);return i?new e(this.start,r,o,l):new e(l,a,n,this.end)},e.prototype.add=function(t,i){return new e(this.start.add(t,i),this.startControl.add(t,i),this.endControl.add(t,i),this.end.add(t,i))},e.prototype.reverse=function(){return new e(this.end,this.endControl,this.startControl,this.start)},e}(),my=function(e){return 1===e.type},_y=function(e){var t=e.styles,i=e.bounds,r=ov(t.borderTopLeftRadius,i.width,i.height),s=r[0],n=r[1],o=ov(t.borderTopRightRadius,i.width,i.height),a=o[0],l=o[1],u=ov(t.borderBottomRightRadius,i.width,i.height),A=u[0],c=u[1],h=ov(t.borderBottomLeftRadius,i.width,i.height),d=h[0],p=h[1],f=[];f.push((s+a)/i.width),f.push((d+A)/i.width),f.push((n+p)/i.height),f.push((l+c)/i.height);var v=Math.max.apply(Math,f);v>1&&(s/=v,n/=v,a/=v,l/=v,A/=v,c/=v,d/=v,p/=v);var g=i.width-a,m=i.height-c,_=i.width-A,y=i.height-p,b=t.borderTopWidth,w=t.borderRightWidth,B=t.borderBottomWidth,x=t.borderLeftWidth,P=av(t.paddingTop,e.bounds.width),C=av(t.paddingRight,e.bounds.width),M=av(t.paddingBottom,e.bounds.width),E=av(t.paddingLeft,e.bounds.width);this.topLeftBorderDoubleOuterBox=s>0||n>0?yy(i.left+x/3,i.top+b/3,s-x/3,n-b/3,z_.TOP_LEFT):new fy(i.left+x/3,i.top+b/3),this.topRightBorderDoubleOuterBox=s>0||n>0?yy(i.left+g,i.top+b/3,a-w/3,l-b/3,z_.TOP_RIGHT):new fy(i.left+i.width-w/3,i.top+b/3),this.bottomRightBorderDoubleOuterBox=A>0||c>0?yy(i.left+_,i.top+m,A-w/3,c-B/3,z_.BOTTOM_RIGHT):new fy(i.left+i.width-w/3,i.top+i.height-B/3),this.bottomLeftBorderDoubleOuterBox=d>0||p>0?yy(i.left+x/3,i.top+y,d-x/3,p-B/3,z_.BOTTOM_LEFT):new fy(i.left+x/3,i.top+i.height-B/3),this.topLeftBorderDoubleInnerBox=s>0||n>0?yy(i.left+2*x/3,i.top+2*b/3,s-2*x/3,n-2*b/3,z_.TOP_LEFT):new fy(i.left+2*x/3,i.top+2*b/3),this.topRightBorderDoubleInnerBox=s>0||n>0?yy(i.left+g,i.top+2*b/3,a-2*w/3,l-2*b/3,z_.TOP_RIGHT):new fy(i.left+i.width-2*w/3,i.top+2*b/3),this.bottomRightBorderDoubleInnerBox=A>0||c>0?yy(i.left+_,i.top+m,A-2*w/3,c-2*B/3,z_.BOTTOM_RIGHT):new fy(i.left+i.width-2*w/3,i.top+i.height-2*B/3),this.bottomLeftBorderDoubleInnerBox=d>0||p>0?yy(i.left+2*x/3,i.top+y,d-2*x/3,p-2*B/3,z_.BOTTOM_LEFT):new fy(i.left+2*x/3,i.top+i.height-2*B/3),this.topLeftBorderStroke=s>0||n>0?yy(i.left+x/2,i.top+b/2,s-x/2,n-b/2,z_.TOP_LEFT):new fy(i.left+x/2,i.top+b/2),this.topRightBorderStroke=s>0||n>0?yy(i.left+g,i.top+b/2,a-w/2,l-b/2,z_.TOP_RIGHT):new fy(i.left+i.width-w/2,i.top+b/2),this.bottomRightBorderStroke=A>0||c>0?yy(i.left+_,i.top+m,A-w/2,c-B/2,z_.BOTTOM_RIGHT):new fy(i.left+i.width-w/2,i.top+i.height-B/2),this.bottomLeftBorderStroke=d>0||p>0?yy(i.left+x/2,i.top+y,d-x/2,p-B/2,z_.BOTTOM_LEFT):new fy(i.left+x/2,i.top+i.height-B/2),this.topLeftBorderBox=s>0||n>0?yy(i.left,i.top,s,n,z_.TOP_LEFT):new fy(i.left,i.top),this.topRightBorderBox=a>0||l>0?yy(i.left+g,i.top,a,l,z_.TOP_RIGHT):new fy(i.left+i.width,i.top),this.bottomRightBorderBox=A>0||c>0?yy(i.left+_,i.top+m,A,c,z_.BOTTOM_RIGHT):new fy(i.left+i.width,i.top+i.height),this.bottomLeftBorderBox=d>0||p>0?yy(i.left,i.top+y,d,p,z_.BOTTOM_LEFT):new fy(i.left,i.top+i.height),this.topLeftPaddingBox=s>0||n>0?yy(i.left+x,i.top+b,Math.max(0,s-x),Math.max(0,n-b),z_.TOP_LEFT):new fy(i.left+x,i.top+b),this.topRightPaddingBox=a>0||l>0?yy(i.left+Math.min(g,i.width-w),i.top+b,g>i.width+w?0:Math.max(0,a-w),Math.max(0,l-b),z_.TOP_RIGHT):new fy(i.left+i.width-w,i.top+b),this.bottomRightPaddingBox=A>0||c>0?yy(i.left+Math.min(_,i.width-x),i.top+Math.min(m,i.height-B),Math.max(0,A-w),Math.max(0,c-B),z_.BOTTOM_RIGHT):new fy(i.left+i.width-w,i.top+i.height-B),this.bottomLeftPaddingBox=d>0||p>0?yy(i.left+x,i.top+Math.min(y,i.height-B),Math.max(0,d-x),Math.max(0,p-B),z_.BOTTOM_LEFT):new fy(i.left+x,i.top+i.height-B),this.topLeftContentBox=s>0||n>0?yy(i.left+x+E,i.top+b+P,Math.max(0,s-(x+E)),Math.max(0,n-(b+P)),z_.TOP_LEFT):new fy(i.left+x+E,i.top+b+P),this.topRightContentBox=a>0||l>0?yy(i.left+Math.min(g,i.width+x+E),i.top+b+P,g>i.width+x+E?0:a-x+E,l-(b+P),z_.TOP_RIGHT):new fy(i.left+i.width-(w+C),i.top+b+P),this.bottomRightContentBox=A>0||c>0?yy(i.left+Math.min(_,i.width-(x+E)),i.top+Math.min(m,i.height+b+P),Math.max(0,A-(w+C)),c-(B+M),z_.BOTTOM_RIGHT):new fy(i.left+i.width-(w+C),i.top+i.height-(B+M)),this.bottomLeftContentBox=d>0||p>0?yy(i.left+x+E,i.top+y,Math.max(0,d-(x+E)),p-(B+M),z_.BOTTOM_LEFT):new fy(i.left+x+E,i.top+i.height-(B+M))};!function(e){e[e.TOP_LEFT=0]="TOP_LEFT",e[e.TOP_RIGHT=1]="TOP_RIGHT",e[e.BOTTOM_RIGHT=2]="BOTTOM_RIGHT",e[e.BOTTOM_LEFT=3]="BOTTOM_LEFT"}(z_||(z_={}));var yy=function(e,t,i,r,s){var n=(Math.sqrt(2)-1)/3*4,o=i*n,a=r*n,l=e+i,u=t+r;switch(s){case z_.TOP_LEFT:return new gy(new fy(e,u),new fy(e,u-a),new fy(l-o,t),new fy(l,t));case z_.TOP_RIGHT:return new gy(new fy(e,t),new fy(e+o,t),new fy(l,u-a),new fy(l,u));case z_.BOTTOM_RIGHT:return new gy(new fy(l,t),new fy(l,t+a),new fy(e+o,u),new fy(e,u));case z_.BOTTOM_LEFT:default:return new gy(new fy(l,u),new fy(l-o,u),new fy(e,t+a),new fy(e,t))}},by=function(e){return[e.topLeftBorderBox,e.topRightBorderBox,e.bottomRightBorderBox,e.bottomLeftBorderBox]},wy=function(e){return[e.topLeftPaddingBox,e.topRightPaddingBox,e.bottomRightPaddingBox,e.bottomLeftPaddingBox]},By=function(e,t,i){this.offsetX=e,this.offsetY=t,this.matrix=i,this.type=0,this.target=6},xy=function(e,t){this.path=e,this.target=t,this.type=1},Py=function(e){this.opacity=e,this.type=2,this.target=6},Cy=function(e){return 1===e.type},My=function(e,t){return e.length===t.length&&e.some((function(e,i){return e===t[i]}))},Ey=function(e){this.element=e,this.inlineLevel=[],this.nonInlineLevel=[],this.negativeZIndex=[],this.zeroOrAutoZIndexOrTransformedOrOpacity=[],this.positiveZIndex=[],this.nonPositionedFloats=[],this.nonPositionedInlineLevel=[]},Fy=function(){function e(e,t){if(this.container=e,this.parent=t,this.effects=[],this.curves=new _y(this.container),this.container.styles.opacity<1&&this.effects.push(new Py(this.container.styles.opacity)),null!==this.container.styles.transform){var i=this.container.bounds.left+this.container.styles.transformOrigin[0].number,r=this.container.bounds.top+this.container.styles.transformOrigin[1].number,s=this.container.styles.transform;this.effects.push(new By(i,r,s))}if(0!==this.container.styles.overflowX){var n=by(this.curves),o=wy(this.curves);My(n,o)?this.effects.push(new xy(n,6)):(this.effects.push(new xy(n,2)),this.effects.push(new xy(o,4)))}}return e.prototype.getEffects=function(e){for(var t=-1===[2,3].indexOf(this.container.styles.position),i=this.parent,r=this.effects.slice(0);i;){var s=i.effects.filter((function(e){return!Cy(e)}));if(t||0!==i.container.styles.position||!i.parent){if(r.unshift.apply(r,s),t=-1===[2,3].indexOf(i.container.styles.position),0!==i.container.styles.overflowX){var n=by(i.curves),o=wy(i.curves);My(n,o)||r.unshift(new xy(o,6))}}else r.unshift.apply(r,s);i=i.parent}return r.filter((function(t){return tm(t.target,e)}))},e}(),ky=function e(t,i,r,s){t.container.elements.forEach((function(n){var o=tm(n.flags,4),a=tm(n.flags,2),l=new Fy(n,t);tm(n.styles.display,2048)&&s.push(l);var u=tm(n.flags,8)?[]:s;if(o||a){var A=o||n.styles.isPositioned()?r:i,c=new Ey(l);if(n.styles.isPositioned()||n.styles.opacity<1||n.styles.isTransformed()){var h=n.styles.zIndex.order;if(h<0){var d=0;A.negativeZIndex.some((function(e,t){return h>e.element.container.styles.zIndex.order?(d=t,!1):d>0})),A.negativeZIndex.splice(d,0,c)}else if(h>0){var p=0;A.positiveZIndex.some((function(e,t){return h>=e.element.container.styles.zIndex.order?(p=t+1,!1):p>0})),A.positiveZIndex.splice(p,0,c)}else A.zeroOrAutoZIndexOrTransformedOrOpacity.push(c)}else n.styles.isFloating()?A.nonPositionedFloats.push(c):A.nonPositionedInlineLevel.push(c);e(l,c,o?c:r,u)}else n.styles.isInlineLevel()?i.inlineLevel.push(l):i.nonInlineLevel.push(l),e(l,i,r,u);tm(n.flags,8)&&Iy(n,u)}))},Iy=function(e,t){for(var i=e instanceof t_?e.start:1,r=e instanceof t_&&e.reversed,s=0;s0&&e.intrinsicHeight>0){var r=Uy(e),s=wy(t);this.path(s),this.ctx.save(),this.ctx.clip(),this.ctx.drawImage(i,0,0,e.intrinsicWidth,e.intrinsicHeight,r.left,r.top,r.width,r.height),this.ctx.restore()}},t.prototype.renderNodeContent=function(e){return up(this,void 0,void 0,(function(){var i,r,s,n,o,a,l,u,A,c,h,d,p,f,v,g,m,_;return Ap(this,(function(y){switch(y.label){case 0:this.applyEffects(e.getEffects(4)),i=e.container,r=e.curves,s=i.styles,n=0,o=i.textNodes,y.label=1;case 1:return n0&&B>0&&(g=r.ctx.createPattern(p,"repeat"),r.renderRepeat(_,g,P,C))):function(e){return 2===e.type}(i)&&(m=Oy(e,t,[null,null,null]),_=m[0],y=m[1],b=m[2],w=m[3],B=m[4],x=0===i.position.length?[sv]:i.position,P=av(x[0],w),C=av(x[x.length-1],B),M=function(e,t,i,r,s){var n=0,o=0;switch(e.size){case 0:0===e.shape?n=o=Math.min(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.min(Math.abs(t),Math.abs(t-r)),o=Math.min(Math.abs(i),Math.abs(i-s)));break;case 2:if(0===e.shape)n=o=Math.min(Ev(t,i),Ev(t,i-s),Ev(t-r,i),Ev(t-r,i-s));else if(1===e.shape){var a=Math.min(Math.abs(i),Math.abs(i-s))/Math.min(Math.abs(t),Math.abs(t-r)),l=Fv(r,s,t,i,!0),u=l[0],A=l[1];o=a*(n=Ev(u-t,(A-i)/a))}break;case 1:0===e.shape?n=o=Math.max(Math.abs(t),Math.abs(t-r),Math.abs(i),Math.abs(i-s)):1===e.shape&&(n=Math.max(Math.abs(t),Math.abs(t-r)),o=Math.max(Math.abs(i),Math.abs(i-s)));break;case 3:if(0===e.shape)n=o=Math.max(Ev(t,i),Ev(t,i-s),Ev(t-r,i),Ev(t-r,i-s));else if(1===e.shape){a=Math.max(Math.abs(i),Math.abs(i-s))/Math.max(Math.abs(t),Math.abs(t-r));var c=Fv(r,s,t,i,!1);u=c[0],A=c[1],o=a*(n=Ev(u-t,(A-i)/a))}}return Array.isArray(e.size)&&(n=av(e.size[0],r),o=2===e.size.length?av(e.size[1],s):n),[n,o]}(i,P,C,w,B),E=M[0],F=M[1],E>0&&F>0&&(k=r.ctx.createRadialGradient(y+P,b+C,0,y+P,b+C,E),Cv(i.stops,2*E).forEach((function(e){return k.addColorStop(e.stop,pv(e.color))})),r.path(_),r.ctx.fillStyle=k,E!==F?(I=e.bounds.left+.5*e.bounds.width,D=e.bounds.top+.5*e.bounds.height,T=1/(S=F/E),r.ctx.save(),r.ctx.translate(I,D),r.ctx.transform(1,0,0,S,0,0),r.ctx.translate(-I,-D),r.ctx.fillRect(y,T*(b-D)+D,w,B*T),r.ctx.restore()):r.ctx.fill())),L.label=6;case 6:return t--,[2]}}))},r=this,s=0,n=e.styles.backgroundImage.slice(0).reverse(),a.label=1;case 1:return s0?2!==l.style?[3,5]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,2)]:[3,11]:[3,13];case 4:return A.sent(),[3,11];case 5:return 3!==l.style?[3,7]:[4,this.renderDashedDottedBorder(l.color,l.width,n,e.curves,3)];case 6:return A.sent(),[3,11];case 7:return 4!==l.style?[3,9]:[4,this.renderDoubleBorder(l.color,l.width,n,e.curves)];case 8:return A.sent(),[3,11];case 9:return[4,this.renderSolidBorder(l.color,n,e.curves)];case 10:A.sent(),A.label=11;case 11:n++,A.label=12;case 12:return o++,[3,3];case 13:return[2]}}))}))},t.prototype.renderDashedDottedBorder=function(e,t,i,r,s){return up(this,void 0,void 0,(function(){var n,o,a,l,u,A,c,h,d,p,f,v,g,m,_,y;return Ap(this,(function(b){return this.ctx.save(),n=function(e,t){switch(t){case 0:return Ty(e.topLeftBorderStroke,e.topRightBorderStroke);case 1:return Ty(e.topRightBorderStroke,e.bottomRightBorderStroke);case 2:return Ty(e.bottomRightBorderStroke,e.bottomLeftBorderStroke);default:return Ty(e.bottomLeftBorderStroke,e.topLeftBorderStroke)}}(r,i),o=Sy(r,i),2===s&&(this.path(o),this.ctx.clip()),my(o[0])?(a=o[0].start.x,l=o[0].start.y):(a=o[0].x,l=o[0].y),my(o[1])?(u=o[1].end.x,A=o[1].end.y):(u=o[1].x,A=o[1].y),c=0===i||2===i?Math.abs(a-u):Math.abs(l-A),this.ctx.beginPath(),3===s?this.formatPath(n):this.formatPath(o.slice(0,2)),h=t<3?3*t:2*t,d=t<3?2*t:t,3===s&&(h=t,d=t),p=!0,c<=2*h?p=!1:c<=2*h+d?(h*=f=c/(2*h+d),d*=f):(v=Math.floor((c+d)/(h+d)),g=(c-v*h)/(v-1),d=(m=(c-(v+1)*h)/v)<=0||Math.abs(d-g)0&&void 0!==arguments[0]?arguments[0]:{},t=!this._snapshotBegun,i=void 0!==e.width&&void 0!==e.height,r=this.scene.canvas.canvas,s=r.clientWidth,n=r.clientHeight,o=e.width?Math.floor(e.width):r.width,a=e.height?Math.floor(e.height):r.height;i&&(r.width=o,r.height=a),this._snapshotBegun||this.beginSnapshot({width:o,height:a}),e.includeGizmos||this.sendToPlugins("snapshotStarting");for(var l={},u=0,A=this._plugins.length;u0&&void 0!==b[0]?b[0]:{},i=!this._snapshotBegun,r=void 0!==t.width&&void 0!==t.height,s=this.scene.canvas.canvas,n=s.clientWidth,o=s.clientHeight,l=t.width?Math.floor(t.width):s.width,u=t.height?Math.floor(t.height):s.height,r&&(s.width=l,s.height=u),this._snapshotBegun||this.beginSnapshot(),t.includeGizmos||this.sendToPlugins("snapshotStarting"),this.scene._renderer.renderSnapshot(),A=this.scene._renderer.readSnapshotAsCanvas(),r&&(s.width=n,s.height=o,this.scene.glRedraw()),c={},h=[],d=0,p=this._plugins.length;d1&&void 0!==arguments[1])||arguments[1],i=arguments.length>2?arguments[2]:void 0,r=i||new Set;if(e){if(Bb(e))r.add(e);else if(Bb(e.buffer))r.add(e.buffer);else if(ArrayBuffer.isView(e));else if(t&&"object"===B(e))for(var s in e)wb(e[s],t,r)}else;return void 0===i?Array.from(r):[]}function Bb(e){return!!e&&(e instanceof ArrayBuffer||("undefined"!=typeof MessagePort&&e instanceof MessagePort||("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)))}var xb=function(){},Pb=function(){function e(t){x(this,e),vb(this,"name",void 0),vb(this,"source",void 0),vb(this,"url",void 0),vb(this,"terminated",!1),vb(this,"worker",void 0),vb(this,"onMessage",void 0),vb(this,"onError",void 0),vb(this,"_loadableURL","");var i=t.name,r=t.source,s=t.url;ub(r||s),this.name=i,this.source=r,this.url=s,this.onMessage=xb,this.onError=function(e){return console.log(e)},this.worker=hb?this._createBrowserWorker():this._createNodeWorker()}return C(e,[{key:"destroy",value:function(){this.onMessage=xb,this.onError=xb,this.worker.terminate(),this.terminated=!0}},{key:"isRunning",get:function(){return Boolean(this.onMessage)}},{key:"postMessage",value:function(e,t){t=t||wb(e),this.worker.postMessage(e,t)}},{key:"_getErrorFromErrorEvent",value:function(e){var t="Failed to load ";return t+="worker ".concat(this.name," from ").concat(this.url,". "),e.message&&(t+="".concat(e.message," in ")),e.lineno&&(t+=":".concat(e.lineno,":").concat(e.colno)),new Error(t)}},{key:"_createBrowserWorker",value:function(){var e=this;this._loadableURL=yb({source:this.source,url:this.url});var t=new Worker(this._loadableURL,{name:this.name});return t.onmessage=function(t){t.data?e.onMessage(t.data):e.onError(new Error("No data received"))},t.onerror=function(t){e.onError(e._getErrorFromErrorEvent(t)),e.terminated=!0},t.onmessageerror=function(e){return console.error(e)},t}},{key:"_createNodeWorker",value:function(){var e,t=this;if(this.url){var i=this.url.includes(":/")||this.url.startsWith("/")?this.url:"./".concat(this.url);e=new mb(i,{eval:!1})}else{if(!this.source)throw new Error("no worker");e=new mb(this.source,{eval:!0})}return e.on("message",(function(e){t.onMessage(e)})),e.on("error",(function(e){t.onError(e)})),e.on("exit",(function(e){})),e}}],[{key:"isSupported",value:function(){return"undefined"!=typeof Worker&&hb||void 0!==B(mb)}}]),e}(),Cb=function(){function e(t){x(this,e),vb(this,"name","unnamed"),vb(this,"source",void 0),vb(this,"url",void 0),vb(this,"maxConcurrency",1),vb(this,"maxMobileConcurrency",1),vb(this,"onDebug",(function(){})),vb(this,"reuseWorkers",!0),vb(this,"props",{}),vb(this,"jobQueue",[]),vb(this,"idleQueue",[]),vb(this,"count",0),vb(this,"isDestroyed",!1),this.source=t.source,this.url=t.url,this.setProps(t)}var t,i;return C(e,[{key:"destroy",value:function(){this.idleQueue.forEach((function(e){return e.destroy()})),this.isDestroyed=!0}},{key:"setProps",value:function(e){this.props=n(n({},this.props),e),void 0!==e.name&&(this.name=e.name),void 0!==e.maxConcurrency&&(this.maxConcurrency=e.maxConcurrency),void 0!==e.maxMobileConcurrency&&(this.maxMobileConcurrency=e.maxMobileConcurrency),void 0!==e.reuseWorkers&&(this.reuseWorkers=e.reuseWorkers),void 0!==e.onDebug&&(this.onDebug=e.onDebug)}},{key:"startJob",value:(i=u(a().mark((function e(t){var i,r,s,n=this,o=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=o.length>1&&void 0!==o[1]?o[1]:function(e,t,i){return e.done(i)},r=o.length>2&&void 0!==o[2]?o[2]:function(e,t){return e.error(t)},s=new Promise((function(e){return n.jobQueue.push({name:t,onMessage:i,onError:r,onStart:e}),n})),this._startQueuedJob(),e.next=6,s;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e,this)}))),function(e){return i.apply(this,arguments)})},{key:"_startQueuedJob",value:(t=u(a().mark((function e(){var t,i,r;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(this.jobQueue.length){e.next=2;break}return e.abrupt("return");case 2:if(t=this._getAvailableWorker()){e.next=5;break}return e.abrupt("return");case 5:if(!(i=this.jobQueue.shift())){e.next=18;break}return this.onDebug({message:"Starting job",name:i.name,workerThread:t,backlog:this.jobQueue.length}),r=new gb(i.name,t),t.onMessage=function(e){return i.onMessage(r,e.type,e.payload)},t.onError=function(e){return i.onError(r,e)},i.onStart(r),e.prev=12,e.next=15,r.result;case 15:return e.prev=15,this.returnWorkerToQueue(t),e.finish(15);case 18:case"end":return e.stop()}}),e,this,[[12,,15,18]])}))),function(){return t.apply(this,arguments)})},{key:"returnWorkerToQueue",value:function(e){this.isDestroyed||!this.reuseWorkers||this.count>this._getMaxConcurrency()?(e.destroy(),this.count--):this.idleQueue.push(e),this.isDestroyed||this._startQueuedJob()}},{key:"_getAvailableWorker",value:function(){if(this.idleQueue.length>0)return this.idleQueue.shift()||null;if(this.count0&&void 0!==arguments[0]?arguments[0]:{};return e._workerFarm=e._workerFarm||new e({}),e._workerFarm.setProps(t),e._workerFarm}}]),e}();vb(Eb,"_workerFarm",void 0);function Fb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t[e.id]||{},r="".concat(e.id,"-worker.js"),s=i.workerUrl;if(s||"compression"!==e.id||(s=t.workerUrl),"test"===t._workerType&&(s="modules/".concat(e.module,"/dist/").concat(r)),!s){var n=e.version;"latest"===n&&(n="latest");var o=n?"@".concat(n):"";s="https://unpkg.com/@loaders.gl/".concat(e.module).concat(o,"/dist/").concat(r)}return ub(s),s}function kb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"3.2.6";ub(e,"no worker provided");var i=e.version;return!(!t||!i)}var Ib=Object.freeze({__proto__:null,default:{}}),Db={};function Sb(e){return Tb.apply(this,arguments)}function Tb(){return Tb=u(a().mark((function e(t){var i,r,s=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=s.length>1&&void 0!==s[1]?s[1]:null,r=s.length>2&&void 0!==s[2]?s[2]:{},i&&(t=Lb(t,i,r)),Db[t]=Db[t]||Rb(t),e.next=6,Db[t];case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)}))),Tb.apply(this,arguments)}function Lb(e,t,i){if(e.startsWith("http"))return e;var r=i.modules||{};return r[e]?r[e]:hb?i.CDN?(ub(i.CDN.startsWith("http")),"".concat(i.CDN,"/").concat(t,"@").concat("3.2.6","/dist/libs/").concat(e)):db?"../src/libs/".concat(e):"modules/".concat(t,"/src/libs/").concat(e):"modules/".concat(t,"/dist/libs/").concat(e)}function Rb(e){return Ub.apply(this,arguments)}function Ub(){return(Ub=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.endsWith("wasm")){e.next=7;break}return e.next=3,fetch(t);case 3:return i=e.sent,e.next=6,i.arrayBuffer();case 6:return e.abrupt("return",e.sent);case 7:if(hb){e.next=20;break}if(e.prev=8,e.t0=Ib&&void 0,!e.t0){e.next=14;break}return e.next=13,(void 0)(t);case 13:e.t0=e.sent;case 14:return e.abrupt("return",e.t0);case 17:return e.prev=17,e.t1=e.catch(8),e.abrupt("return",null);case 20:if(!db){e.next=22;break}return e.abrupt("return",importScripts(t));case 22:return e.next=24,fetch(t);case 24:return r=e.sent,e.next=27,r.text();case 27:return s=e.sent,e.abrupt("return",Ob(s,t));case 29:case"end":return e.stop()}}),e,null,[[8,17]])})))).apply(this,arguments)}function Ob(e,t){if(hb){if(db)return eval.call(cb,e),null;var i=document.createElement("script");i.id=t;try{i.appendChild(document.createTextNode(e))}catch(t){i.text=e}return document.body.appendChild(i),null}}function Nb(e,t){return!!Eb.isSupported()&&(!!(hb||null!=t&&t._nodeWorkers)&&(e.worker&&(null==t?void 0:t.worker)))}function Qb(e,t,i,r,s){return Vb.apply(this,arguments)}function Vb(){return Vb=u(a().mark((function e(t,i,r,s,n){var o,l,u,A,c,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return o=t.id,l=Fb(t,r),u=Eb.getWorkerFarm(r),A=u.getWorkerPool({name:o,url:l}),r=JSON.parse(JSON.stringify(r)),s=JSON.parse(JSON.stringify(s||{})),e.next=8,A.startJob("process-on-worker",Hb.bind(null,n));case 8:return(c=e.sent).postMessage("process",{input:i,options:r,context:s}),e.next=12,c.result;case 12:return h=e.sent,e.next=15,h.result;case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e)}))),Vb.apply(this,arguments)}function Hb(e,t,i,r){return jb.apply(this,arguments)}function jb(){return(jb=u(a().mark((function e(t,i,r,s){var n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:e.t0=r,e.next="done"===e.t0?3:"error"===e.t0?5:"process"===e.t0?7:20;break;case 3:return i.done(s),e.abrupt("break",21);case 5:return i.error(new Error(s.error)),e.abrupt("break",21);case 7:return n=s.id,o=s.input,l=s.options,e.prev=8,e.next=11,t(o,l);case 11:u=e.sent,i.postMessage("done",{id:n,result:u}),e.next=19;break;case 15:e.prev=15,e.t1=e.catch(8),A=e.t1 instanceof Error?e.t1.message:"unknown error",i.postMessage("error",{id:n,error:A});case 19:return e.abrupt("break",21);case 20:console.warn("parse-with-worker unknown message ".concat(r));case 21:case"end":return e.stop()}}),e,null,[[8,15]])})))).apply(this,arguments)}function Gb(e,t,i){if(e.byteLength<=t+i)return"";for(var r=new DataView(e),s="",n=0;n1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return Gb(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){return Gb(e,0,t)}return""}(e),'"'))}}function Wb(e){return e&&"object"===B(e)&&e.isBuffer}function Kb(e){if(Wb(e))return Wb(t=e)?new Uint8Array(t.buffer,t.byteOffset,t.length).slice().buffer:t;var t;if(e instanceof ArrayBuffer)return e;if(ArrayBuffer.isView(e))return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);if("string"==typeof e){var i=e;return(new TextEncoder).encode(i).buffer}if(e&&"object"===B(e)&&e._toArrayBuffer)return e._toArrayBuffer();throw new Error("toArrayBuffer")}function Xb(){for(var e=arguments.length,t=new Array(e),i=0;i=0),ob(t>0),e+(t-1)&~(t-1)}function Zb(e,t,i){var r;if(e instanceof ArrayBuffer)r=new Uint8Array(e);else{var s=e.byteOffset,n=e.byteLength;r=new Uint8Array(e.buffer||e.arrayBuffer,s,n)}return t.set(r,i),i+Jb(r.byteLength,4)}function qb(e){return $b.apply(this,arguments)}function $b(){return($b=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=[],r=!1,s=!1,e.prev=3,o=I(t);case 5:return e.next=7,o.next();case 7:if(!(r=!(l=e.sent).done)){e.next=13;break}u=l.value,i.push(u);case 10:r=!1,e.next=5;break;case 13:e.next=19;break;case 15:e.prev=15,e.t0=e.catch(3),s=!0,n=e.t0;case 19:if(e.prev=19,e.prev=20,!r||null==o.return){e.next=24;break}return e.next=24,o.return();case 24:if(e.prev=24,!s){e.next=27;break}throw n;case 27:return e.finish(24);case 28:return e.finish(19);case 29:return e.abrupt("return",Xb.apply(void 0,i));case 30:case"end":return e.stop()}}),e,null,[[3,15,19,29],[20,,24,28]])})))).apply(this,arguments)}var ew={};function tw(e){for(var t in ew)if(e.startsWith(t)){var i=ew[t];e=e.replace(t,i)}return e.startsWith("http://")||e.startsWith("https://")||(e="".concat("").concat(e)),e}var iw=function(e){return"function"==typeof e},rw=function(e){return null!==e&&"object"===B(e)},sw=function(e){return rw(e)&&e.constructor==={}.constructor},nw=function(e){return e&&"function"==typeof e[Symbol.iterator]},ow=function(e){return e&&"function"==typeof e[Symbol.asyncIterator]},aw=function(e){return"undefined"!=typeof Response&&e instanceof Response||e&&e.arrayBuffer&&e.text&&e.json},lw=function(e){return"undefined"!=typeof Blob&&e instanceof Blob},uw=function(e){return function(e){return"undefined"!=typeof ReadableStream&&e instanceof ReadableStream||rw(e)&&iw(e.tee)&&iw(e.cancel)&&iw(e.getReader)}(e)||function(e){return rw(e)&&iw(e.read)&&iw(e.pipe)&&function(e){return"boolean"==typeof e}(e.readable)}(e)},Aw=/^data:([-\w.]+\/[-\w.+]+)(;|,)/,cw=/^([-\w.]+\/[-\w.+]+)/;function hw(e){var t=cw.exec(e);return t?t[1]:e}function dw(e){var t=Aw.exec(e);return t?t[1]:""}var pw=/\?.*/;function fw(e){if(aw(e)){var t=gw(e.url||"");return{url:t,type:hw(e.headers.get("content-type")||"")||dw(t)}}return lw(e)?{url:gw(e.name||""),type:e.type||""}:"string"==typeof e?{url:gw(e),type:dw(e)}:{url:"",type:""}}function vw(e){return aw(e)?e.headers["content-length"]||-1:lw(e)?e.size:"string"==typeof e?e.length:e instanceof ArrayBuffer||ArrayBuffer.isView(e)?e.byteLength:-1}function gw(e){return e.replace(pw,"")}function mw(e){return _w.apply(this,arguments)}function _w(){return(_w=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!aw(t)){e.next=2;break}return e.abrupt("return",t);case 2:return i={},(r=vw(t))>=0&&(i["content-length"]=String(r)),s=fw(t),n=s.url,(o=s.type)&&(i["content-type"]=o),e.next=9,xw(t);case 9:return(l=e.sent)&&(i["x-first-bytes"]=l),"string"==typeof t&&(t=(new TextEncoder).encode(t)),u=new Response(t,{headers:i}),Object.defineProperty(u,"url",{value:n}),e.abrupt("return",u);case 15:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function yw(e){return bw.apply(this,arguments)}function bw(){return(bw=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(t.ok){e.next=5;break}return e.next=3,ww(t);case 3:throw i=e.sent,new Error(i);case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ww(e){return Bw.apply(this,arguments)}function Bw(){return(Bw=u(a().mark((function e(t){var i,r,s;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i="Failed to fetch resource ".concat(t.url," (").concat(t.status,"): "),e.prev=1,r=t.headers.get("Content-Type"),s=t.statusText,!r.includes("application/json")){e.next=11;break}return e.t0=s,e.t1=" ",e.next=9,t.text();case 9:e.t2=e.sent,s=e.t0+=e.t1.concat.call(e.t1,e.t2);case 11:i=(i+=s).length>60?"".concat(i.slice(0,60),"..."):i,e.next=17;break;case 15:e.prev=15,e.t3=e.catch(1);case 17:return e.abrupt("return",i);case 18:case"end":return e.stop()}}),e,null,[[1,15]])})))).apply(this,arguments)}function xw(e){return Pw.apply(this,arguments)}function Pw(){return(Pw=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=5,"string"!=typeof t){e.next=3;break}return e.abrupt("return","data:,".concat(t.slice(0,i)));case 3:if(!(t instanceof Blob)){e.next=8;break}return r=t.slice(0,5),e.next=7,new Promise((function(e){var t=new FileReader;t.onload=function(t){var i;return e(null==t||null===(i=t.target)||void 0===i?void 0:i.result)},t.readAsDataURL(r)}));case 7:return e.abrupt("return",e.sent);case 8:if(!(t instanceof ArrayBuffer)){e.next=12;break}return s=t.slice(0,i),n=Cw(s),e.abrupt("return","data:base64,".concat(n));case 12:return e.abrupt("return",null);case 13:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function Cw(e){for(var t="",i=new Uint8Array(e),r=0;r=0)}();function Tw(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}var Lw=function(){function e(t,i){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";x(this,e),this.storage=Tw(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function Rw(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}var Uw={BLACK:30,RED:31,GREEN:32,YELLOW:33,BLUE:34,MAGENTA:35,CYAN:36,WHITE:37,BRIGHT_BLACK:90,BRIGHT_RED:91,BRIGHT_GREEN:92,BRIGHT_YELLOW:93,BRIGHT_BLUE:94,BRIGHT_MAGENTA:95,BRIGHT_CYAN:96,BRIGHT_WHITE:97};function Ow(e){return"string"==typeof e?Uw[e.toUpperCase()]||Uw.WHITE:e}function Nw(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function Qw(e,t){if(!e)throw new Error(t||"Assertion failed")}function Vw(){var e;if(Sw&&kw.performance)e=kw.performance.now();else if(Iw.hrtime){var t=Iw.hrtime();e=1e3*t[0]+t[1]/1e6}else e=Date.now();return e}var Hw={debug:Sw&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},jw={enabled:!0,level:0};function Gw(){}var zw={},Ww={once:!0};function Kw(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}var Xw=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;x(this,e),this.id=i,this.VERSION=Dw,this._startTs=Vw(),this._deltaTs=Vw(),this.LOG_THROTTLE_TIMEOUT=0,this._storage=new Lw("__probe-".concat(this.id,"__"),jw),this.userData={},this.timeStamp("".concat(this.id," started")),Nw(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((Vw()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((Vw()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"assert",value:function(e,t){Qw(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,Hw.warn,arguments,Ww)}},{key:"error",value:function(e){return this._getLogFunction(0,e,Hw.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,Hw.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,Hw.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){return this._getLogFunction(e,t,Hw.debug||Hw.info,arguments,Ww)}},{key:"table",value:function(e,t,i){return t?this._getLogFunction(e,t,console.table||Gw,i&&[i],{tag:Kw(t)}):Gw}},{key:"image",value:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e){var t=e.logLevel,i=e.priority,r=e.image,s=e.message,n=void 0===s?"":s,o=e.scale,a=void 0===o?1:o;return this._shouldLog(t||i)?Sw?function(e){var t=e.image,i=e.message,r=void 0===i?"":i,s=e.scale,n=void 0===s?1:s;if("string"==typeof t){var o=new Image;return o.onload=function(){var e,t=Rw(o,r,n);(e=console).log.apply(e,A(t))},o.src=t,Gw}var a=t.nodeName||"";if("img"===a.toLowerCase()){var l;return(l=console).log.apply(l,A(Rw(t,r,n))),Gw}if("canvas"===a.toLowerCase()){var u=new Image;return u.onload=function(){var e;return(e=console).log.apply(e,A(Rw(u,r,n)))},u.src=t.toDataURL(),Gw}return Gw}({image:r,message:n,scale:a}):function(e){var t=e.image,i=(e.message,e.scale),r=void 0===i?1:i,s=null;try{s=module.require("asciify-image")}catch(e){}if(s)return function(){return s(t,{fit:"box",width:"".concat(Math.round(80*r),"%")}).then((function(e){return console.log(e)}))};return Gw}({image:r,message:n,scale:a}):Gw}))},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"time",value:function(e,t){return this._getLogFunction(e,t,console.time?console.time:console.info)}},{key:"timeEnd",value:function(e,t){return this._getLogFunction(e,t,console.timeEnd?console.timeEnd:console.info)}},{key:"timeStamp",value:function(e,t){return this._getLogFunction(e,t,console.timeStamp||Gw)}},{key:"group",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=i=Jw({logLevel:e,message:t,opts:i}),s=r.collapsed;return i.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(i)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||Gw)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=Yw(e)}},{key:"_getLogFunction",value:function(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[],s=arguments.length>4?arguments[4]:void 0;if(this._shouldLog(e)){var n;s=Jw({logLevel:e,message:t,args:r,opts:s}),Qw(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=Vw();var o=s.tag||s.message;if(s.once){if(zw[o])return Gw;zw[o]=Vw()}return t=Zw(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(A(s.args)))}return Gw}}]),e}();function Yw(e){if(!e)return 0;var t;switch(B(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return Qw(Number.isFinite(t)&&t>=0),t}function Jw(e){var t=e.logLevel,i=e.message;e.logLevel=Yw(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(e.args=r,B(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=B(e.message);return Qw("string"===s||"object"===s),Object.assign(e,e.opts)}function Zw(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return Sw||"string"!=typeof e||(t&&(t=Ow(t),e="[".concat(t,"m").concat(e,"")),i&&(t=Ow(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}Xw.VERSION=Dw;var qw=new Xw({id:"loaders.gl"}),$w=function(){function e(){x(this,e)}return C(e,[{key:"log",value:function(){return function(){}}},{key:"info",value:function(){return function(){}}},{key:"warn",value:function(){return function(){}}},{key:"error",value:function(){return function(){}}}]),e}(),eB={fetch:null,mimeType:void 0,nothrow:!1,log:new(function(){function e(){x(this,e),vb(this,"console",void 0),this.console=console}return C(e,[{key:"log",value:function(){for(var e,t=arguments.length,i=new Array(t),r=0;r=0)}()}var dB={self:"undefined"!=typeof self&&self,window:"undefined"!=typeof window&&window,global:"undefined"!=typeof global&&global,document:"undefined"!=typeof document&&document,process:"object"===("undefined"==typeof process?"undefined":B(process))&&process},pB=dB.window||dB.self||dB.global,fB=dB.process||{},vB="undefined"!=typeof __VERSION__?__VERSION__:"untranspiled source";function gB(e){try{var t=window[e],i="__storage_test__";return t.setItem(i,i),t.removeItem(i),t}catch(e){return null}}hB();var mB,_B=function(){function e(t){x(this,e);var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"sessionStorage";vb(this,"storage",void 0),vb(this,"id",void 0),vb(this,"config",{}),this.storage=gB(r),this.id=t,this.config={},Object.assign(this.config,i),this._loadConfiguration()}return C(e,[{key:"getConfiguration",value:function(){return this.config}},{key:"setConfiguration",value:function(e){return this.config={},this.updateConfiguration(e)}},{key:"updateConfiguration",value:function(e){if(Object.assign(this.config,e),this.storage){var t=JSON.stringify(this.config);this.storage.setItem(this.id,t)}return this}},{key:"_loadConfiguration",value:function(){var e={};if(this.storage){var t=this.storage.getItem(this.id);e=t?JSON.parse(t):{}}return Object.assign(this.config,e),this}}]),e}();function yB(e,t,i){var r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:600,s=e.src.replace(/\(/g,"%28").replace(/\)/g,"%29");e.width>r&&(i=Math.min(i,r/e.width));var n=e.width*i,o=e.height*i,a=["font-size:1px;","padding:".concat(Math.floor(o/2),"px ").concat(Math.floor(n/2),"px;"),"line-height:".concat(o,"px;"),"background:url(".concat(s,");"),"background-size:".concat(n,"px ").concat(o,"px;"),"color:transparent;"].join("");return["".concat(t," %c+"),a]}function bB(e){return"string"==typeof e?mB[e.toUpperCase()]||mB.WHITE:e}function wB(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:["constructor"],r=Object.getPrototypeOf(e),s=Object.getOwnPropertyNames(r),n=c(s);try{var o=function(){var r=t.value;"function"==typeof e[r]&&(i.find((function(e){return r===e}))||(e[r]=e[r].bind(e)))};for(n.s();!(t=n.n()).done;)o()}catch(e){n.e(e)}finally{n.f()}}function BB(e,t){if(!e)throw new Error(t||"Assertion failed")}function xB(){var e,t,i;if(hB&&"performance"in pB)e=null==pB||null===(t=pB.performance)||void 0===t||null===(i=t.now)||void 0===i?void 0:i.call(t);else if("hrtime"in fB){var r,s=null==fB||null===(r=fB.hrtime)||void 0===r?void 0:r.call(fB);e=1e3*s[0]+s[1]/1e6}else e=Date.now();return e}!function(e){e[e.BLACK=30]="BLACK",e[e.RED=31]="RED",e[e.GREEN=32]="GREEN",e[e.YELLOW=33]="YELLOW",e[e.BLUE=34]="BLUE",e[e.MAGENTA=35]="MAGENTA",e[e.CYAN=36]="CYAN",e[e.WHITE=37]="WHITE",e[e.BRIGHT_BLACK=90]="BRIGHT_BLACK",e[e.BRIGHT_RED=91]="BRIGHT_RED",e[e.BRIGHT_GREEN=92]="BRIGHT_GREEN",e[e.BRIGHT_YELLOW=93]="BRIGHT_YELLOW",e[e.BRIGHT_BLUE=94]="BRIGHT_BLUE",e[e.BRIGHT_MAGENTA=95]="BRIGHT_MAGENTA",e[e.BRIGHT_CYAN=96]="BRIGHT_CYAN",e[e.BRIGHT_WHITE=97]="BRIGHT_WHITE"}(mB||(mB={}));var PB={debug:hB&&console.debug||console.log,log:console.log,info:console.info,warn:console.warn,error:console.error},CB={enabled:!0,level:0};function MB(){}var EB={},FB={once:!0},kB=function(){function e(){x(this,e);var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{id:""},i=t.id;vb(this,"id",void 0),vb(this,"VERSION",vB),vb(this,"_startTs",xB()),vb(this,"_deltaTs",xB()),vb(this,"_storage",void 0),vb(this,"userData",{}),vb(this,"LOG_THROTTLE_TIMEOUT",0),this.id=i,this._storage=new _B("__probe-".concat(this.id,"__"),CB),this.userData={},this.timeStamp("".concat(this.id," started")),wB(this),Object.seal(this)}return C(e,[{key:"level",get:function(){return this.getLevel()},set:function(e){this.setLevel(e)}},{key:"isEnabled",value:function(){return this._storage.config.enabled}},{key:"getLevel",value:function(){return this._storage.config.level}},{key:"getTotal",value:function(){return Number((xB()-this._startTs).toPrecision(10))}},{key:"getDelta",value:function(){return Number((xB()-this._deltaTs).toPrecision(10))}},{key:"priority",get:function(){return this.level},set:function(e){this.level=e}},{key:"getPriority",value:function(){return this.level}},{key:"enable",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return this._storage.updateConfiguration({enabled:e}),this}},{key:"setLevel",value:function(e){return this._storage.updateConfiguration({level:e}),this}},{key:"get",value:function(e){return this._storage.config[e]}},{key:"set",value:function(e,t){this._storage.updateConfiguration(o({},e,t))}},{key:"settings",value:function(){console.table?console.table(this._storage.config):console.log(this._storage.config)}},{key:"assert",value:function(e,t){BB(e,t)}},{key:"warn",value:function(e){return this._getLogFunction(0,e,PB.warn,arguments,FB)}},{key:"error",value:function(e){return this._getLogFunction(0,e,PB.error,arguments)}},{key:"deprecated",value:function(e,t){return this.warn("`".concat(e,"` is deprecated and will be removed in a later version. Use `").concat(t,"` instead"))}},{key:"removed",value:function(e,t){return this.error("`".concat(e,"` has been removed. Use `").concat(t,"` instead"))}},{key:"probe",value:function(e,t){return this._getLogFunction(e,t,PB.log,arguments,{time:!0,once:!0})}},{key:"log",value:function(e,t){return this._getLogFunction(e,t,PB.debug,arguments)}},{key:"info",value:function(e,t){return this._getLogFunction(e,t,console.info,arguments)}},{key:"once",value:function(e,t){for(var i=arguments.length,r=new Array(i>2?i-2:0),s=2;s2&&void 0!==arguments[2]?arguments[2]:{collapsed:!1},r=DB({logLevel:e,message:t,opts:i}),s=i.collapsed;return r.method=(s?console.groupCollapsed:console.group)||console.info,this._getLogFunction(r)}},{key:"groupCollapsed",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return this.group(e,t,Object.assign({},i,{collapsed:!0}))}},{key:"groupEnd",value:function(e){return this._getLogFunction(e,"",console.groupEnd||MB)}},{key:"withGroup",value:function(e,t,i){this.group(e,t)();try{i()}finally{this.groupEnd(e)()}}},{key:"trace",value:function(){console.trace&&console.trace()}},{key:"_shouldLog",value:function(e){return this.isEnabled()&&this.getLevel()>=IB(e)}},{key:"_getLogFunction",value:function(e,t,i,r,s){if(this._shouldLog(e)){var n;s=DB({logLevel:e,message:t,args:r,opts:s}),BB(i=i||s.method),s.total=this.getTotal(),s.delta=this.getDelta(),this._deltaTs=xB();var o=s.tag||s.message;if(s.once){if(EB[o])return MB;EB[o]=xB()}return t=function(e,t,i){if("string"==typeof t){var r=i.time?function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:8,i=Math.max(t-e.length,0);return"".concat(" ".repeat(i)).concat(e)}((s=i.total)<10?"".concat(s.toFixed(2),"ms"):s<100?"".concat(s.toFixed(1),"ms"):s<1e3?"".concat(s.toFixed(0),"ms"):"".concat((s/1e3).toFixed(2),"s")):"";t=function(e,t,i){return hB||"string"!=typeof e||(t&&(t=bB(t),e="[".concat(t,"m").concat(e,"")),i&&(t=bB(i),e="[".concat(i+10,"m").concat(e,""))),e}(t=i.time?"".concat(e,": ").concat(r," ").concat(t):"".concat(e,": ").concat(t),i.color,i.background)}var s;return t}(this.id,s.message,s),(n=i).bind.apply(n,[console,t].concat(A(s.args)))}return MB}}]),e}();function IB(e){if(!e)return 0;var t;switch(B(e)){case"number":t=e;break;case"object":t=e.logLevel||e.priority||0;break;default:return 0}return BB(Number.isFinite(t)&&t>=0),t}function DB(e){var t=e.logLevel,i=e.message;e.logLevel=IB(t);for(var r=e.args?Array.from(e.args):[];r.length&&r.shift()!==i;);switch(B(t)){case"string":case"function":void 0!==i&&r.unshift(i),e.message=t;break;case"object":Object.assign(e,t)}"function"==typeof e.message&&(e.message=e.message());var s=B(e.message);return BB("string"===s||"object"===s),Object.assign(e,{args:r},e.opts)}function SB(e){for(var t in e)for(var i in e[t])return i||"untitled";return"empty"}vb(kB,"VERSION",vB);var TB=new kB({id:"loaders.gl"}),LB=/\.([^.]+)$/;function RB(e){return UB.apply(this,arguments)}function UB(){return UB=u(a().mark((function e(t){var i,r,s,o,l=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=l.length>1&&void 0!==l[1]?l[1]:[],r=l.length>2?l[2]:void 0,s=l.length>3?l[3]:void 0,QB(t)){e.next=5;break}return e.abrupt("return",null);case 5:if(!(o=OB(t,i,n(n({},r),{},{nothrow:!0}),s))){e.next=8;break}return e.abrupt("return",o);case 8:if(!lw(t)){e.next=13;break}return e.next=11,t.slice(0,10).arrayBuffer();case 11:t=e.sent,o=OB(t,i,r,s);case 13:if(o||null!=r&&r.nothrow){e.next=15;break}throw new Error(VB(t));case 15:return e.abrupt("return",o);case 16:case"end":return e.stop()}}),e)}))),UB.apply(this,arguments)}function OB(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,r=arguments.length>3?arguments[3]:void 0;if(!QB(e))return null;if(t&&!Array.isArray(t))return AB(t);var s,n=[];(t&&(n=n.concat(t)),null!=i&&i.ignoreRegisteredLoaders)||(s=n).push.apply(s,A(cB()));HB(n);var o=NB(e,n,i,r);if(!(o||null!=i&&i.nothrow))throw new Error(VB(e));return o}function NB(e,t,i,r){var s,n=fw(e),o=n.url,a=n.type,l=o||(null==r?void 0:r.url),u=null,A="";(null!=i&&i.mimeType&&(u=jB(t,null==i?void 0:i.mimeType),A="match forced by supplied MIME type ".concat(null==i?void 0:i.mimeType)),u=u||function(e,t){var i=t&&LB.exec(t),r=i&&i[1];return r?function(e,t){t=t.toLowerCase();var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s,n=i.value,o=c(n.extensions);try{for(o.s();!(s=o.n()).done;){if(s.value.toLowerCase()===t)return n}}catch(e){o.e(e)}finally{o.f()}}}catch(e){r.e(e)}finally{r.f()}return null}(e,r):null}(t,l),A=A||(u?"matched url ".concat(l):""),u=u||jB(t,a),A=A||(u?"matched MIME type ".concat(a):""),u=u||function(e,t){if(!t)return null;var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if("string"==typeof t){if(GB(t,s))return s}else if(ArrayBuffer.isView(t)){if(zB(t.buffer,t.byteOffset,s))return s}else if(t instanceof ArrayBuffer){if(zB(t,0,s))return s}}}catch(e){r.e(e)}finally{r.f()}return null}(t,e),A=A||(u?"matched initial data ".concat(WB(e)):""),u=u||jB(t,null==i?void 0:i.fallbackMimeType),A=A||(u?"matched fallback MIME type ".concat(a):""))&&TB.log(1,"selectLoader selected ".concat(null===(s=u)||void 0===s?void 0:s.name,": ").concat(A,"."));return u}function QB(e){return!(e instanceof Response&&204===e.status)}function VB(e){var t=fw(e),i=t.url,r=t.type,s="No valid loader found (";s+=i?"".concat(function(e){var t=e&&e.lastIndexOf("/");return t>=0?e.substr(t+1):""}(i),", "):"no url provided, ",s+="MIME type: ".concat(r?'"'.concat(r,'"'):"not provided",", ");var n=e?WB(e):"";return s+=n?' first bytes: "'.concat(n,'"'):"first bytes: not available",s+=")"}function HB(e){var t,i=c(e);try{for(i.s();!(t=i.n()).done;){AB(t.value)}}catch(e){i.e(e)}finally{i.f()}}function jB(e,t){var i,r=c(e);try{for(r.s();!(i=r.n()).done;){var s=i.value;if(s.mimeTypes&&s.mimeTypes.includes(t))return s;if(t==="application/x.".concat(s.id))return s}}catch(e){r.e(e)}finally{r.f()}return null}function GB(e,t){return t.testText?t.testText(e):(Array.isArray(t.tests)?t.tests:[t.tests]).some((function(t){return e.startsWith(t)}))}function zB(e,t,i){return(Array.isArray(i.tests)?i.tests:[i.tests]).some((function(r){return function(e,t,i,r){if(r instanceof ArrayBuffer)return function(e,t,i){if(i=i||e.byteLength,e.byteLength1&&void 0!==arguments[1]?arguments[1]:5;if("string"==typeof e)return e.slice(0,t);if(ArrayBuffer.isView(e))return KB(e.buffer,e.byteOffset,t);if(e instanceof ArrayBuffer){var i=0;return KB(e,i,t)}return""}function KB(e,t,i){if(e.byteLength1&&void 0!==A[1]?A[1]:{},r=t.chunkSize,s=void 0===r?262144:r,n=0;case 3:if(!(n2&&void 0!==arguments[2]?arguments[2]:null;if(i)return i;var r=n({fetch:nB(t,e)},e);return Array.isArray(r.loaders)||(r.loaders=null),r}function ox(e,t){if(!t&&e&&!Array.isArray(e))return e;var i;if(e&&(i=Array.isArray(e)?e:[e]),t&&t.loaders){var r=Array.isArray(t.loaders)?t.loaders:[t.loaders];i=i?[].concat(A(i),A(r)):r}return i&&i.length?i:null}function ax(e,t,i,r){return lx.apply(this,arguments)}function lx(){return(lx=u(a().mark((function e(t,i,r,s){var n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return ub(!s||"object"===B(s)),!i||Array.isArray(i)||uB(i)||(s=void 0,r=i,i=void 0),e.next=4,t;case 4:return t=e.sent,r=r||{},n=fw(t),o=n.url,l=ox(i,s),e.next=11,RB(t,l,r);case 11:if(u=e.sent){e.next=14;break}return e.abrupt("return",null);case 14:return r=sB(r,u,l,o),s=nx({url:o,parse:ax,loaders:l},r,s),e.next=18,ux(u,t,r,s);case 18:return e.abrupt("return",e.sent);case 19:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function ux(e,t,i,r){return Ax.apply(this,arguments)}function Ax(){return(Ax=u(a().mark((function e(t,i,r,s){var n,o,l,u,A,c,h,d;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return kb(t),aw(i)&&(o=(n=i).ok,l=n.redirected,u=n.status,A=n.statusText,c=n.type,h=n.url,d=Object.fromEntries(n.headers.entries()),s.response={headers:d,ok:o,redirected:l,status:u,statusText:A,type:c,url:h}),e.next=4,rx(i,t,r);case 4:if(i=e.sent,!t.parseTextSync||"string"!=typeof i){e.next=8;break}return r.dataType="text",e.abrupt("return",t.parseTextSync(i,r,s,t));case 8:if(!Nb(t,r)){e.next=12;break}return e.next=11,Qb(t,i,r,s,ax);case 11:case 15:case 19:return e.abrupt("return",e.sent);case 12:if(!t.parseText||"string"!=typeof i){e.next=16;break}return e.next=15,t.parseText(i,r,s,t);case 16:if(!t.parse){e.next=20;break}return e.next=19,t.parse(i,r,s,t);case 20:throw ub(!t.parseSync),new Error("".concat(t.id," loader - no parser found and worker is disabled"));case 22:case"end":return e.stop()}}),e)})))).apply(this,arguments)}var cx,hx,dx="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.wasm"),px="https://unpkg.com/@loaders.gl/textures@".concat("3.2.6","/dist/libs/basis_encoder.js");function fx(e){return vx.apply(this,arguments)}function vx(){return(vx=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basis){e.next=3;break}return e.abrupt("return",i.basis);case 3:return cx=cx||gx(t),e.next=6,cx;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function gx(e){return mx.apply(this,arguments)}function mx(){return(mx=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Sb("basis_transcoder.js","textures",t);case 5:return e.t1=e.sent,e.next=8,Sb("basis_transcoder.wasm","textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=h(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,_x(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function _x(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile;(0,e.initializeBasis)(),t({BasisFile:i})}))}))}function yx(e){return bx.apply(this,arguments)}function bx(){return(bx=u(a().mark((function e(t){var i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!(i=t.modules||{}).basisEncoder){e.next=3;break}return e.abrupt("return",i.basisEncoder);case 3:return hx=hx||wx(t),e.next=6,hx;case 6:return e.abrupt("return",e.sent);case 7:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function wx(e){return Bx.apply(this,arguments)}function Bx(){return(Bx=u(a().mark((function e(t){var i,r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return i=null,r=null,e.t0=Promise,e.next=5,Sb(px,"textures",t);case 5:return e.t1=e.sent,e.next=8,Sb(dx,"textures",t);case 8:return e.t2=e.sent,e.t3=[e.t1,e.t2],e.next=12,e.t0.all.call(e.t0,e.t3);case 12:return s=e.sent,n=h(s,2),i=n[0],r=n[1],i=i||globalThis.BASIS,e.next=19,xx(i,r);case 19:return e.abrupt("return",e.sent);case 20:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function xx(e,t){var i={};return t&&(i.wasmBinary=t),new Promise((function(t){e(i).then((function(e){var i=e.BasisFile,r=e.KTX2File,s=e.initializeBasis,n=e.BasisEncoder;s(),t({BasisFile:i,KTX2File:r,BasisEncoder:n})}))}))}var Px,Cx,Mx,Ex,Fx,kx,Ix,Dx,Sx,Tx=33776,Lx=33779,Rx=35840,Ux=35842,Ox=36196,Nx=37808,Qx=["","WEBKIT_","MOZ_"],Vx={WEBGL_compressed_texture_s3tc:"dxt",WEBGL_compressed_texture_s3tc_srgb:"dxt-srgb",WEBGL_compressed_texture_etc1:"etc1",WEBGL_compressed_texture_etc:"etc2",WEBGL_compressed_texture_pvrtc:"pvrtc",WEBGL_compressed_texture_atc:"atc",WEBGL_compressed_texture_astc:"astc",EXT_texture_compression_rgtc:"rgtc"},Hx=null;function jx(e){if(!Hx){e=e||function(){try{return document.createElement("canvas").getContext("webgl")}catch(e){return null}}()||void 0,Hx=new Set;var t,i=c(Qx);try{for(i.s();!(t=i.n()).done;){var r=t.value;for(var s in Vx)if(e&&e.getExtension("".concat(r).concat(s))){var n=Vx[s];Hx.add(n)}}}catch(e){i.e(e)}finally{i.f()}}return Hx}(Sx=Px||(Px={}))[Sx.NONE=0]="NONE",Sx[Sx.BASISLZ=1]="BASISLZ",Sx[Sx.ZSTD=2]="ZSTD",Sx[Sx.ZLIB=3]="ZLIB",function(e){e[e.BASICFORMAT=0]="BASICFORMAT"}(Cx||(Cx={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.ETC1S=163]="ETC1S",e[e.UASTC=166]="UASTC"}(Mx||(Mx={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.SRGB=1]="SRGB"}(Ex||(Ex={})),function(e){e[e.UNSPECIFIED=0]="UNSPECIFIED",e[e.LINEAR=1]="LINEAR",e[e.SRGB=2]="SRGB",e[e.ITU=3]="ITU",e[e.NTSC=4]="NTSC",e[e.SLOG=5]="SLOG",e[e.SLOG2=6]="SLOG2"}(Fx||(Fx={})),function(e){e[e.ALPHA_STRAIGHT=0]="ALPHA_STRAIGHT",e[e.ALPHA_PREMULTIPLIED=1]="ALPHA_PREMULTIPLIED"}(kx||(kx={})),function(e){e[e.RGB=0]="RGB",e[e.RRR=3]="RRR",e[e.GGG=4]="GGG",e[e.AAA=15]="AAA"}(Ix||(Ix={})),function(e){e[e.RGB=0]="RGB",e[e.RGBA=3]="RGBA",e[e.RRR=4]="RRR",e[e.RRRG=5]="RRRG"}(Dx||(Dx={}));var Gx=[171,75,84,88,32,50,48,187,13,10,26,10];function zx(e){var t=new Uint8Array(e);return!(t.byteLength1&&void 0!==r[1]?r[1]:null)&&mP||(i=null),!i){e.next=13;break}return e.prev=3,e.next=6,createImageBitmap(t,i);case 6:return e.abrupt("return",e.sent);case 9:e.prev=9,e.t0=e.catch(3),console.warn(e.t0),mP=!1;case 13:return e.next=15,createImageBitmap(t);case 15:return e.abrupt("return",e.sent);case 16:case"end":return e.stop()}}),e,null,[[3,9]])}))),wP.apply(this,arguments)}function BP(e){for(var t in e||gP)return!1;return!0}function xP(e){var t=PP(e);return function(e){var t=PP(e);if(!(t.byteLength>=24&&2303741511===t.getUint32(0,false)))return null;return{mimeType:"image/png",width:t.getUint32(16,false),height:t.getUint32(20,false)}}(t)||function(e){var t=PP(e);if(!(t.byteLength>=3&&65496===t.getUint16(0,false)&&255===t.getUint8(2)))return null;var i=function(){for(var e=new Set([65499,65476,65484,65501,65534]),t=65504;t<65520;++t)e.add(t);var i=new Set([65472,65473,65474,65475,65477,65478,65479,65481,65482,65483,65485,65486,65487,65502]);return{tableMarkers:e,sofMarkers:i}}(),r=i.tableMarkers,s=i.sofMarkers,n=2;for(;n+9=10&&1195984440===t.getUint32(0,false)))return null;return{mimeType:"image/gif",width:t.getUint16(6,true),height:t.getUint16(8,true)}}(t)||function(e){var t=PP(e);if(!(t.byteLength>=14&&16973===t.getUint16(0,false)&&t.getUint32(2,true)===t.byteLength))return null;return{mimeType:"image/bmp",width:t.getUint32(18,true),height:t.getUint32(22,true)}}(t)}function PP(e){if(e instanceof DataView)return e;if(ArrayBuffer.isView(e))return new DataView(e.buffer);if(e instanceof ArrayBuffer)return new DataView(e);throw new Error("toDataView")}function CP(e,t){return MP.apply(this,arguments)}function MP(){return MP=u(a().mark((function e(t,i){var r,s,n;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return r=xP(t)||{},s=r.mimeType,ob(n=globalThis._parseImageNode),e.next=5,n(t,s);case 5:return e.abrupt("return",e.sent);case 6:case"end":return e.stop()}}),e)}))),MP.apply(this,arguments)}function EP(){return(EP=u(a().mark((function e(t,i,r){var s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=(i=i||{}).image||{},n=s.type||"auto",o=(r||{}).url,l=FP(n),e.t0=l,e.next="imagebitmap"===e.t0?8:"image"===e.t0?12:"data"===e.t0?16:20;break;case 8:return e.next=10,_P(t,i,o);case 10:return u=e.sent,e.abrupt("break",21);case 12:return e.next=14,dP(t,i,o);case 14:return u=e.sent,e.abrupt("break",21);case 16:return e.next=18,CP(t);case 18:return u=e.sent,e.abrupt("break",21);case 20:ob(!1);case 21:return"data"===n&&(u=aP(u)),e.abrupt("return",u);case 23:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function FP(e){switch(e){case"auto":case"data":return function(){if(rP)return"imagebitmap";if(iP)return"image";if(nP)return"data";throw new Error("Install '@loaders.gl/polyfills' to parse images under Node.js")}();default:return function(e){switch(e){case"auto":return rP||iP||nP;case"imagebitmap":return rP;case"image":return iP;case"data":return nP;default:throw new Error("@loaders.gl/images: image ".concat(e," not supported in this environment"))}}(e),e}}var kP={id:"image",module:"images",name:"Images",version:"3.2.6",mimeTypes:["image/png","image/jpeg","image/gif","image/webp","image/bmp","image/vnd.microsoft.icon","image/svg+xml"],extensions:["png","jpg","jpeg","gif","webp","bmp","ico","svg"],parse:function(e,t,i){return EP.apply(this,arguments)},tests:[function(e){return Boolean(xP(new DataView(e)))}],options:{image:{type:"auto",decode:!0}}},IP=["image/png","image/jpeg","image/gif"],DP={};function SP(e){return void 0===DP[e]&&(DP[e]=function(e){switch(e){case"image/webp":return function(){if(!ab)return!1;try{return 0===document.createElement("canvas").toDataURL("image/webp").indexOf("data:image/webp")}catch(e){return!1}}();case"image/svg":return ab;default:if(!ab){var t=globalThis._parseImageNode;return Boolean(t)&&IP.includes(e)}return!0}}(e)),DP[e]}function TP(e,t){if(!e)throw new Error(t||"assert failed: gltf")}function LP(e,t){if(e.startsWith("data:")||e.startsWith("http:")||e.startsWith("https:"))return e;var i=t.baseUri||t.uri;if(!i)throw new Error("'baseUri' must be provided to resolve relative url ".concat(e));return i.substr(0,i.lastIndexOf("/")+1)+e}function RP(e,t,i){var r=e.bufferViews[i];TP(r);var s=t[r.buffer];TP(s);var n=(r.byteOffset||0)+s.byteOffset;return new Uint8Array(s.arrayBuffer,n,r.byteLength)}var UP=["SCALAR","VEC2","VEC3","VEC4"],OP=[[Int8Array,5120],[Uint8Array,5121],[Int16Array,5122],[Uint16Array,5123],[Uint32Array,5125],[Float32Array,5126],[Float64Array,5130]],NP=new Map(OP),QP={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},VP={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},HP={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array};function jP(e){return UP[e-1]||UP[0]}function GP(e){var t=NP.get(e.constructor);if(!t)throw new Error("Illegal typed array");return t}function zP(e,t){var i=HP[e.componentType],r=QP[e.type],s=VP[e.componentType],n=e.count*r,o=e.count*r*s;return TP(o>=0&&o<=t.byteLength),{ArrayType:i,length:n,byteLength:o}}var WP,KP={asset:{version:"2.0",generator:"loaders.gl"},buffers:[]},XP=function(){function e(t){x(this,e),vb(this,"gltf",void 0),vb(this,"sourceBuffers",void 0),vb(this,"byteLength",void 0),this.gltf=t||{json:n({},KP),buffers:[]},this.sourceBuffers=[],this.byteLength=0,this.gltf.buffers&&this.gltf.buffers[0]&&(this.byteLength=this.gltf.buffers[0].byteLength,this.sourceBuffers=[this.gltf.buffers[0]])}return C(e,[{key:"json",get:function(){return this.gltf.json}},{key:"getApplicationData",value:function(e){return this.json[e]}},{key:"getExtraData",value:function(e){return(this.json.extras||{})[e]}},{key:"getExtension",value:function(e){var t=this.getUsedExtensions().find((function(t){return t===e})),i=this.json.extensions||{};return t?i[e]||!0:null}},{key:"getRequiredExtension",value:function(e){var t=this.getRequiredExtensions().find((function(t){return t===e}));return t?this.getExtension(e):null}},{key:"getRequiredExtensions",value:function(){return this.json.extensionsRequired||[]}},{key:"getUsedExtensions",value:function(){return this.json.extensionsUsed||[]}},{key:"getObjectExtension",value:function(e,t){return(e.extensions||{})[t]}},{key:"getScene",value:function(e){return this.getObject("scenes",e)}},{key:"getNode",value:function(e){return this.getObject("nodes",e)}},{key:"getSkin",value:function(e){return this.getObject("skins",e)}},{key:"getMesh",value:function(e){return this.getObject("meshes",e)}},{key:"getMaterial",value:function(e){return this.getObject("materials",e)}},{key:"getAccessor",value:function(e){return this.getObject("accessors",e)}},{key:"getTexture",value:function(e){return this.getObject("textures",e)}},{key:"getSampler",value:function(e){return this.getObject("samplers",e)}},{key:"getImage",value:function(e){return this.getObject("images",e)}},{key:"getBufferView",value:function(e){return this.getObject("bufferViews",e)}},{key:"getBuffer",value:function(e){return this.getObject("buffers",e)}},{key:"getObject",value:function(e,t){if("object"===B(t))return t;var i=this.json[e]&&this.json[e][t];if(!i)throw new Error("glTF file error: Could not find ".concat(e,"[").concat(t,"]"));return i}},{key:"getTypedArrayForBufferView",value:function(e){var t=(e=this.getBufferView(e)).buffer,i=this.gltf.buffers[t];TP(i);var r=(e.byteOffset||0)+i.byteOffset;return new Uint8Array(i.arrayBuffer,r,e.byteLength)}},{key:"getTypedArrayForAccessor",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=zP(e,t),s=r.ArrayType,n=r.length;return new s(i,t.byteOffset+e.byteOffset,n)}},{key:"getTypedArrayForImageData",value:function(e){e=this.getAccessor(e);var t=this.getBufferView(e.bufferView),i=this.getBuffer(t.buffer).data,r=t.byteOffset||0;return new Uint8Array(i,r,t.byteLength)}},{key:"addApplicationData",value:function(e,t){return this.json[e]=t,this}},{key:"addExtraData",value:function(e,t){return this.json.extras=this.json.extras||{},this.json.extras[e]=t,this}},{key:"addObjectExtension",value:function(e,t,i){return e.extensions=e.extensions||{},e.extensions[t]=i,this.registerUsedExtension(t),this}},{key:"setObjectExtension",value:function(e,t,i){(e.extensions||{})[t]=i}},{key:"removeObjectExtension",value:function(e,t){var i=e.extensions||{},r=i[t];return delete i[t],r}},{key:"addExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return TP(t),this.json.extensions=this.json.extensions||{},this.json.extensions[e]=t,this.registerUsedExtension(e),t}},{key:"addRequiredExtension",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return TP(t),this.addExtension(e,t),this.registerRequiredExtension(e),t}},{key:"registerUsedExtension",value:function(e){this.json.extensionsUsed=this.json.extensionsUsed||[],this.json.extensionsUsed.find((function(t){return t===e}))||this.json.extensionsUsed.push(e)}},{key:"registerRequiredExtension",value:function(e){this.registerUsedExtension(e),this.json.extensionsRequired=this.json.extensionsRequired||[],this.json.extensionsRequired.find((function(t){return t===e}))||this.json.extensionsRequired.push(e)}},{key:"removeExtension",value:function(e){this.json.extensionsRequired&&this._removeStringFromArray(this.json.extensionsRequired,e),this.json.extensionsUsed&&this._removeStringFromArray(this.json.extensionsUsed,e),this.json.extensions&&delete this.json.extensions[e]}},{key:"setDefaultScene",value:function(e){this.json.scene=e}},{key:"addScene",value:function(e){var t=e.nodeIndices;return this.json.scenes=this.json.scenes||[],this.json.scenes.push({nodes:t}),this.json.scenes.length-1}},{key:"addNode",value:function(e){var t=e.meshIndex,i=e.matrix;this.json.nodes=this.json.nodes||[];var r={mesh:t};return i&&(r.matrix=i),this.json.nodes.push(r),this.json.nodes.length-1}},{key:"addMesh",value:function(e){var t=e.attributes,i=e.indices,r=e.material,s=e.mode,n=void 0===s?4:s,o={primitives:[{attributes:this._addAttributes(t),mode:n}]};if(i){var a=this._addIndices(i);o.primitives[0].indices=a}return Number.isFinite(r)&&(o.primitives[0].material=r),this.json.meshes=this.json.meshes||[],this.json.meshes.push(o),this.json.meshes.length-1}},{key:"addPointCloud",value:function(e){var t={primitives:[{attributes:this._addAttributes(e),mode:0}]};return this.json.meshes=this.json.meshes||[],this.json.meshes.push(t),this.json.meshes.length-1}},{key:"addImage",value:function(e,t){var i=xP(e),r=t||(null==i?void 0:i.mimeType),s={bufferView:this.addBufferView(e),mimeType:r};return this.json.images=this.json.images||[],this.json.images.push(s),this.json.images.length-1}},{key:"addBufferView",value:function(e){var t=e.byteLength;TP(Number.isFinite(t)),this.sourceBuffers=this.sourceBuffers||[],this.sourceBuffers.push(e);var i={buffer:0,byteOffset:this.byteLength,byteLength:t};return this.byteLength+=Jb(t,4),this.json.bufferViews=this.json.bufferViews||[],this.json.bufferViews.push(i),this.json.bufferViews.length-1}},{key:"addAccessor",value:function(e,t){var i={bufferView:e,type:jP(t.size),componentType:t.componentType,count:t.count,max:t.max,min:t.min};return this.json.accessors=this.json.accessors||[],this.json.accessors.push(i),this.json.accessors.length-1}},{key:"addBinaryBuffer",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{size:3},i=this.addBufferView(e),r={min:t.min,max:t.max};r.min&&r.max||(r=this._getAccessorMinMax(e,t.size));var s={size:t.size,componentType:GP(e),count:Math.round(e.length/t.size),min:r.min,max:r.max};return this.addAccessor(i,Object.assign(s,t))}},{key:"addTexture",value:function(e){var t={source:e.imageIndex};return this.json.textures=this.json.textures||[],this.json.textures.push(t),this.json.textures.length-1}},{key:"addMaterial",value:function(e){return this.json.materials=this.json.materials||[],this.json.materials.push(e),this.json.materials.length-1}},{key:"createBinaryChunk",value:function(){var e,t;this.gltf.buffers=[];var i,r=this.byteLength,s=new ArrayBuffer(r),n=new Uint8Array(s),o=0,a=c(this.sourceBuffers||[]);try{for(a.s();!(i=a.n()).done;){o=Zb(i.value,n,o)}}catch(e){a.e(e)}finally{a.f()}null!==(e=this.json)&&void 0!==e&&null!==(t=e.buffers)&&void 0!==t&&t[0]?this.json.buffers[0].byteLength=r:this.json.buffers=[{byteLength:r}],this.gltf.binary=s,this.sourceBuffers=[s]}},{key:"_removeStringFromArray",value:function(e,t){for(var i=!0;i;){var r=e.indexOf(t);r>-1?e.splice(r,1):i=!1}}},{key:"_addAttributes",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t={};for(var i in e){var r=e[i],s=this._getGltfAttributeName(i),n=this.addBinaryBuffer(r.value,r);t[s]=n}return t}},{key:"_addIndices",value:function(e){return this.addBinaryBuffer(e,{size:1})}},{key:"_getGltfAttributeName",value:function(e){switch(e.toLowerCase()){case"position":case"positions":case"vertices":return"POSITION";case"normal":case"normals":return"NORMAL";case"color":case"colors":return"COLOR_0";case"texcoord":case"texcoords":return"TEXCOORD_0";default:return e}}},{key:"_getAccessorMinMax",value:function(e,t){var i={min:null,max:null};if(e.length5&&void 0!==u[5]?u[5]:"NONE",e.next=3,rC();case 3:lC(l=e.sent,l.exports[eC[n]],t,i,r,s,l.exports[$P[o||"NONE"]]);case 5:case"end":return e.stop()}}),e)}))),iC.apply(this,arguments)}function rC(){return sC.apply(this,arguments)}function sC(){return(sC=u(a().mark((function e(){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return WP||(WP=nC()),e.abrupt("return",WP);case 2:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function nC(){return oC.apply(this,arguments)}function oC(){return(oC=u(a().mark((function e(){var t,i;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:return t=YP,WebAssembly.validate(ZP)&&(t=JP,console.log("Warning: meshopt_decoder is using experimental SIMD support")),e.next=4,WebAssembly.instantiate(aC(t),{});case 4:return i=e.sent,e.next=7,i.instance.exports.__wasm_call_ctors();case 7:return e.abrupt("return",i.instance);case 8:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function aC(e){for(var t=new Uint8Array(e.length),i=0;i96?r-71:r>64?r-65:r>47?r+4:r>46?63:62}for(var s=0,n=0;ns?A:s,n=c>n?c:n,o=h>o?h:o}return[[t,i,r],[s,n,o]]}var gC=function(){function e(t,i){x(this,e),vb(this,"fields",void 0),vb(this,"metadata",void 0),function(e,t){if(!e)throw new Error(t||"loader assertion failed.")}(Array.isArray(t)),function(e){var t,i={},r=c(e);try{for(r.s();!(t=r.n()).done;){var s=t.value;i[s.name]&&console.warn("Schema: duplicated field name",s.name,s),i[s.name]=!0}}catch(e){r.e(e)}finally{r.f()}}(t),this.fields=t,this.metadata=i||new Map}return C(e,[{key:"compareTo",value:function(e){if(this.metadata!==e.metadata)return!1;if(this.fields.length!==e.fields.length)return!1;for(var t=0;t2&&void 0!==arguments[2]&&arguments[2],s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:new Map;x(this,e),vb(this,"name",void 0),vb(this,"type",void 0),vb(this,"nullable",void 0),vb(this,"metadata",void 0),this.name=t,this.type=i,this.nullable=r,this.metadata=s}return C(e,[{key:"typeId",get:function(){return this.type&&this.type.typeId}},{key:"clone",value:function(){return new e(this.name,this.type,this.nullable,this.metadata)}},{key:"compareTo",value:function(e){return this.name===e.name&&this.type===e.type&&this.nullable===e.nullable&&this.metadata===e.metadata}},{key:"toString",value:function(){return"".concat(this.type).concat(this.nullable?", nullable":"").concat(this.metadata?", metadata: ".concat(this.metadata):"")}}]),e}();!function(e){e[e.NONE=0]="NONE",e[e.Null=1]="Null",e[e.Int=2]="Int",e[e.Float=3]="Float",e[e.Binary=4]="Binary",e[e.Utf8=5]="Utf8",e[e.Bool=6]="Bool",e[e.Decimal=7]="Decimal",e[e.Date=8]="Date",e[e.Time=9]="Time",e[e.Timestamp=10]="Timestamp",e[e.Interval=11]="Interval",e[e.List=12]="List",e[e.Struct=13]="Struct",e[e.Union=14]="Union",e[e.FixedSizeBinary=15]="FixedSizeBinary",e[e.FixedSizeList=16]="FixedSizeList",e[e.Map=17]="Map",e[e.Dictionary=-1]="Dictionary",e[e.Int8=-2]="Int8",e[e.Int16=-3]="Int16",e[e.Int32=-4]="Int32",e[e.Int64=-5]="Int64",e[e.Uint8=-6]="Uint8",e[e.Uint16=-7]="Uint16",e[e.Uint32=-8]="Uint32",e[e.Uint64=-9]="Uint64",e[e.Float16=-10]="Float16",e[e.Float32=-11]="Float32",e[e.Float64=-12]="Float64",e[e.DateDay=-13]="DateDay",e[e.DateMillisecond=-14]="DateMillisecond",e[e.TimestampSecond=-15]="TimestampSecond",e[e.TimestampMillisecond=-16]="TimestampMillisecond",e[e.TimestampMicrosecond=-17]="TimestampMicrosecond",e[e.TimestampNanosecond=-18]="TimestampNanosecond",e[e.TimeSecond=-19]="TimeSecond",e[e.TimeMillisecond=-20]="TimeMillisecond",e[e.TimeMicrosecond=-21]="TimeMicrosecond",e[e.TimeNanosecond=-22]="TimeNanosecond",e[e.DenseUnion=-23]="DenseUnion",e[e.SparseUnion=-24]="SparseUnion",e[e.IntervalDayTime=-25]="IntervalDayTime",e[e.IntervalYearMonth=-26]="IntervalYearMonth"}(_C||(_C={}));var bC=function(){function e(){x(this,e)}return C(e,[{key:"typeId",get:function(){return _C.NONE}},{key:"compareTo",value:function(e){return this===e}}],[{key:"isNull",value:function(e){return e&&e.typeId===_C.Null}},{key:"isInt",value:function(e){return e&&e.typeId===_C.Int}},{key:"isFloat",value:function(e){return e&&e.typeId===_C.Float}},{key:"isBinary",value:function(e){return e&&e.typeId===_C.Binary}},{key:"isUtf8",value:function(e){return e&&e.typeId===_C.Utf8}},{key:"isBool",value:function(e){return e&&e.typeId===_C.Bool}},{key:"isDecimal",value:function(e){return e&&e.typeId===_C.Decimal}},{key:"isDate",value:function(e){return e&&e.typeId===_C.Date}},{key:"isTime",value:function(e){return e&&e.typeId===_C.Time}},{key:"isTimestamp",value:function(e){return e&&e.typeId===_C.Timestamp}},{key:"isInterval",value:function(e){return e&&e.typeId===_C.Interval}},{key:"isList",value:function(e){return e&&e.typeId===_C.List}},{key:"isStruct",value:function(e){return e&&e.typeId===_C.Struct}},{key:"isUnion",value:function(e){return e&&e.typeId===_C.Union}},{key:"isFixedSizeBinary",value:function(e){return e&&e.typeId===_C.FixedSizeBinary}},{key:"isFixedSizeList",value:function(e){return e&&e.typeId===_C.FixedSizeList}},{key:"isMap",value:function(e){return e&&e.typeId===_C.Map}},{key:"isDictionary",value:function(e){return e&&e.typeId===_C.Dictionary}}]),e}(),wC=function(e,t){g(r,bC);var i=_(r);function r(e,t){var s;return x(this,r),vb(b(s=i.call(this)),"isSigned",void 0),vb(b(s),"bitWidth",void 0),s.isSigned=e,s.bitWidth=t,s}return C(r,[{key:"typeId",get:function(){return _C.Int}},{key:t,get:function(){return"Int"}},{key:"toString",value:function(){return"".concat(this.isSigned?"I":"Ui","nt").concat(this.bitWidth)}}]),r}(0,Symbol.toStringTag),BC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,8)}return C(i)}(),xC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,16)}return C(i)}(),PC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!0,32)}return C(i)}(),CC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,8)}return C(i)}(),MC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,16)}return C(i)}(),EC=function(e){g(i,wC);var t=_(i);function i(){return x(this,i),t.call(this,!1,32)}return C(i)}(),FC=32,kC=64,IC=function(e,t){g(r,bC);var i=_(r);function r(e){var t;return x(this,r),vb(b(t=i.call(this)),"precision",void 0),t.precision=e,t}return C(r,[{key:"typeId",get:function(){return _C.Float}},{key:t,get:function(){return"Float"}},{key:"toString",value:function(){return"Float".concat(this.precision)}}]),r}(0,Symbol.toStringTag),DC=function(e){g(i,IC);var t=_(i);function i(){return x(this,i),t.call(this,FC)}return C(i)}(),SC=function(e){g(i,IC);var t=_(i);function i(){return x(this,i),t.call(this,kC)}return C(i)}(),TC=function(e,t){g(r,bC);var i=_(r);function r(e,t){var s;return x(this,r),vb(b(s=i.call(this)),"listSize",void 0),vb(b(s),"children",void 0),s.listSize=e,s.children=[t],s}return C(r,[{key:"typeId",get:function(){return _C.FixedSizeList}},{key:"valueType",get:function(){return this.children[0].type}},{key:"valueField",get:function(){return this.children[0]}},{key:t,get:function(){return"FixedSizeList"}},{key:"toString",value:function(){return"FixedSizeList[".concat(this.listSize,"]<").concat(this.valueType,">")}}]),r}(0,Symbol.toStringTag);function LC(e,t,i){var r=function(e){switch(e.constructor){case Int8Array:return new BC;case Uint8Array:return new CC;case Int16Array:return new xC;case Uint16Array:return new MC;case Int32Array:return new PC;case Uint32Array:return new EC;case Float32Array:return new DC;case Float64Array:return new SC;default:throw new Error("array type not supported")}}(t.value),s=i||function(e){var t=new Map;"byteOffset"in e&&t.set("byteOffset",e.byteOffset.toString(10));"byteStride"in e&&t.set("byteStride",e.byteStride.toString(10));"normalized"in e&&t.set("normalized",e.normalized.toString());return t}(t);return new yC(e,new TC(t.size,new yC("value",r)),!1,s)}function RC(e,t,i){var r=OC(t.metadata),s=[],n=function(e){var t={};for(var i in e){var r=e[i];t[r.name||"undefined"]=r}return t}(t.attributes);for(var o in e){var a=UC(o,e[o],n[o]);s.push(a)}if(i){var l=UC("indices",i);s.push(l)}return new gC(s,r)}function UC(e,t,i){return LC(e,t,i?OC(i.metadata):void 0)}function OC(e){var t=new Map;for(var i in e)t.set("".concat(i,".string"),JSON.stringify(e[i]));return t}var NC={POSITION:"POSITION",NORMAL:"NORMAL",COLOR:"COLOR_0",TEX_COORD:"TEXCOORD_0"},QC={1:Int8Array,2:Uint8Array,3:Int16Array,4:Uint16Array,5:Int32Array,6:Uint32Array,9:Float32Array},VC=function(){function e(t){x(this,e),vb(this,"draco",void 0),vb(this,"decoder",void 0),vb(this,"metadataQuerier",void 0),this.draco=t,this.decoder=new this.draco.Decoder,this.metadataQuerier=new this.draco.MetadataQuerier}return C(e,[{key:"destroy",value:function(){this.draco.destroy(this.decoder),this.draco.destroy(this.metadataQuerier)}},{key:"parseSync",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new this.draco.DecoderBuffer;i.Init(new Int8Array(e),e.byteLength),this._disableAttributeTransforms(t);var r=this.decoder.GetEncodedGeometryType(i),s=r===this.draco.TRIANGULAR_MESH?new this.draco.Mesh:new this.draco.PointCloud;try{var o;switch(r){case this.draco.TRIANGULAR_MESH:o=this.decoder.DecodeBufferToMesh(i,s);break;case this.draco.POINT_CLOUD:o=this.decoder.DecodeBufferToPointCloud(i,s);break;default:throw new Error("DRACO: Unknown geometry type.")}if(!o.ok()||!s.ptr){var a="DRACO decompression failed: ".concat(o.error_msg());throw new Error(a)}var l=this._getDracoLoaderData(s,r,t),u=this._getMeshData(s,l,t),A=vC(u.attributes),c=RC(u.attributes,l,u.indices),h=n(n({loader:"draco",loaderData:l,header:{vertexCount:s.num_points(),boundingBox:A}},u),{},{schema:c});return h}finally{this.draco.destroy(i),s&&this.draco.destroy(s)}}},{key:"_getDracoLoaderData",value:function(e,t,i){var r=this._getTopLevelMetadata(e),s=this._getDracoAttributes(e,i);return{geometry_type:t,num_attributes:e.num_attributes(),num_points:e.num_points(),num_faces:e instanceof this.draco.Mesh?e.num_faces():0,metadata:r,attributes:s}}},{key:"_getDracoAttributes",value:function(e,t){for(var i={},r=0;r2&&void 0!==arguments[2]&&arguments[2];if(!e)return null;if(Array.isArray(e))return new t(e);if(i&&!(e instanceof t))return new t(e);return e}(t,Float32Array)),r=t.length/i);return{buffer:t,size:i,count:r}}(e),i=t.buffer,r=t.size;return{value:i,size:r,byteOffset:0,count:t.count,type:jP(r),componentType:GP(i)}}function tM(){return(tM=u(a().mark((function e(t,i,r){var s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(null!=i&&null!==(s=i.gltf)&&void 0!==s&&s.decompressMeshes){e.next=2;break}return e.abrupt("return");case 2:n=new XP(t),o=[],l=c(oM(n));try{for(l.s();!(u=l.n()).done;)A=u.value,n.getObjectExtension(A,"KHR_draco_mesh_compression")&&o.push(iM(n,A,i,r))}catch(e){l.e(e)}finally{l.f()}return e.next=8,Promise.all(o);case 8:n.removeExtension("KHR_draco_mesh_compression");case 9:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function iM(e,t,i,r){return rM.apply(this,arguments)}function rM(){return rM=u(a().mark((function e(t,i,r,s){var o,l,u,A,c,d,p,f,v,g,m,_,y,b;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(o=t.getObjectExtension(i,"KHR_draco_mesh_compression")){e.next=3;break}return e.abrupt("return");case 3:return l=t.getTypedArrayForBufferView(o.bufferView),u=Yb(l.buffer,l.byteOffset),A=s.parse,delete(c=n({},r))["3d-tiles"],e.next=10,A(u,ZC,c,s);case 10:for(d=e.sent,p=$C(d.attributes),f=0,v=Object.entries(p);f2&&void 0!==arguments[2]?arguments[2]:4,s=arguments.length>3?arguments[3]:void 0,n=arguments.length>4?arguments[4]:void 0;if(!s.DracoWriter)throw new Error("options.gltf.DracoWriter not provided");var a=s.DracoWriter.encodeSync({attributes:e}),l=null==n||null===(i=n.parseSync)||void 0===i?void 0:i.call(n,{attributes:e}),u=s._addFauxAttributes(l.attributes),A=s.addBufferView(a),c={primitives:[{attributes:u,mode:r,extensions:o({},"KHR_draco_mesh_compression",{bufferView:A,attributes:u})}]};return c}function nM(e){if(!e.attributes&&Object.keys(e.attributes).length>0)throw new Error("glTF: Empty primitive detected: Draco decompression failure?")}function oM(e){var t,i,s,n,o,l;return a().wrap((function(r){for(;;)switch(r.prev=r.next){case 0:t=c(e.json.meshes||[]),r.prev=1,t.s();case 3:if((i=t.n()).done){r.next=24;break}s=i.value,n=c(s.primitives),r.prev=6,n.s();case 8:if((o=n.n()).done){r.next=14;break}return l=o.value,r.next=12,l;case 12:r.next=8;break;case 14:r.next=19;break;case 16:r.prev=16,r.t0=r.catch(6),n.e(r.t0);case 19:return r.prev=19,n.f(),r.finish(19);case 22:r.next=3;break;case 24:r.next=29;break;case 26:r.prev=26,r.t1=r.catch(1),t.e(r.t1);case 29:return r.prev=29,t.f(),r.finish(29);case 32:case"end":return r.stop()}}),r,null,[[1,26,29,32],[6,16,19,22]])}function aM(){return(aM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new XP(t),r=i.json,(s=i.getExtension("KHR_lights_punctual"))&&(i.json.lights=s.lights,i.removeExtension("KHR_lights_punctual")),n=c(r.nodes||[]);try{for(n.s();!(o=n.n()).done;)l=o.value,(u=i.getObjectExtension(l,"KHR_lights_punctual"))&&(l.light=u.light),i.removeObjectExtension(l,"KHR_lights_punctual")}catch(e){n.e(e)}finally{n.f()}case 6:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function lM(){return(lM=u(a().mark((function e(t){var i,r,s,n,o,l,u;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new XP(t),(r=i.json).lights&&(TP(!(s=i.addExtension("KHR_lights_punctual")).lights),s.lights=r.lights,delete r.lights),i.json.lights){n=c(i.json.lights);try{for(n.s();!(o=n.n()).done;)l=o.value,u=l.node,i.addObjectExtension(u,"KHR_lights_punctual",l)}catch(e){n.e(e)}finally{n.f()}delete i.json.lights}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function uM(){return(uM=u(a().mark((function e(t){var i,r,s,n,o;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=new XP(t),r=i.json,i.removeExtension("KHR_materials_unlit"),s=c(r.materials||[]);try{for(s.s();!(n=s.n()).done;)o=n.value,o.extensions&&o.extensions.KHR_materials_unlit&&(o.unlit=!0),i.removeObjectExtension(o,"KHR_materials_unlit")}catch(e){s.e(e)}finally{s.f()}case 5:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function AM(){return(AM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(i=new XP(t),r=i.json,s=i.getExtension("KHR_techniques_webgl")){n=hM(s,i),o=c(r.materials||[]);try{for(o.s();!(l=o.n()).done;)u=l.value,(A=i.getObjectExtension(u,"KHR_techniques_webgl"))&&(u.technique=Object.assign({},A,n[A.technique]),u.technique.values=dM(u.technique,i)),i.removeObjectExtension(u,"KHR_techniques_webgl")}catch(e){o.e(e)}finally{o.f()}i.removeExtension("KHR_techniques_webgl")}case 4:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function cM(){return(cM=u(a().mark((function e(t,i){return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:case"end":return e.stop()}}),e)})))).apply(this,arguments)}function hM(e,t){var i=e.programs,r=void 0===i?[]:i,s=e.shaders,n=void 0===s?[]:s,o=e.techniques,a=void 0===o?[]:o,l=new TextDecoder;return n.forEach((function(e){if(!Number.isFinite(e.bufferView))throw new Error("KHR_techniques_webgl: no shader code");e.code=l.decode(t.getTypedArrayForBufferView(e.bufferView))})),r.forEach((function(e){e.fragmentShader=n[e.fragmentShader],e.vertexShader=n[e.vertexShader]})),a.forEach((function(e){e.program=r[e.program]})),a}function dM(e,t){var i=Object.assign({},e.values);return Object.keys(e.uniforms||{}).forEach((function(t){e.uniforms[t].value&&!(t in i)&&(i[t]=e.uniforms[t].value)})),Object.keys(i).forEach((function(e){"object"===B(i[e])&&void 0!==i[e].index&&(i[e].texture=t.getTexture(i[e].index))})),i}var pM=[hC,dC,pC,Object.freeze({__proto__:null,name:"KHR_draco_mesh_compression",preprocess:function(e,t,i){var r,s=new XP(e),n=c(oM(s));try{for(n.s();!(r=n.n()).done;){var o=r.value;s.getObjectExtension(o,"KHR_draco_mesh_compression")}}catch(e){n.e(e)}finally{n.f()}},decode:function(e,t,i){return tM.apply(this,arguments)},encode:function(e){var t,i=new XP(e),r=c(i.json.meshes||[]);try{for(r.s();!(t=r.n()).done;){var s=t.value;sM(s),i.addRequiredExtension("KHR_draco_mesh_compression")}}catch(e){r.e(e)}finally{r.f()}}}),Object.freeze({__proto__:null,name:"KHR_lights_punctual",decode:function(e){return aM.apply(this,arguments)},encode:function(e){return lM.apply(this,arguments)}}),Object.freeze({__proto__:null,name:"KHR_materials_unlit",decode:function(e){return uM.apply(this,arguments)},encode:function(e){var t=new XP(e),i=t.json;if(t.materials){var r,s=c(i.materials||[]);try{for(s.s();!(r=s.n()).done;){var n=r.value;n.unlit&&(delete n.unlit,t.addObjectExtension(n,"KHR_materials_unlit",{}),t.addExtension("KHR_materials_unlit"))}}catch(e){s.e(e)}finally{s.f()}}}}),Object.freeze({__proto__:null,name:"KHR_techniques_webgl",decode:function(e){return AM.apply(this,arguments)},encode:function(e,t){return cM.apply(this,arguments)}})];function fM(e){var t,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,s=pM.filter((function(e){return mM(e.name,i)})),n=c(s);try{for(n.s();!(t=n.n()).done;){var o,a=t.value;null===(o=a.preprocess)||void 0===o||o.call(a,e,i,r)}}catch(e){n.e(e)}finally{n.f()}}function vM(e){return gM.apply(this,arguments)}function gM(){return gM=u(a().mark((function e(t){var i,r,s,n,o,l,u,A=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:i=A.length>1&&void 0!==A[1]?A[1]:{},r=A.length>2?A[2]:void 0,s=pM.filter((function(e){return mM(e.name,i)})),n=c(s),e.prev=4,n.s();case 6:if((o=n.n()).done){e.next=12;break}return l=o.value,e.next=10,null===(u=l.decode)||void 0===u?void 0:u.call(l,t,i,r);case 10:e.next=6;break;case 12:e.next=17;break;case 14:e.prev=14,e.t0=e.catch(4),n.e(e.t0);case 17:return e.prev=17,n.f(),e.finish(17);case 20:case"end":return e.stop()}}),e,null,[[4,14,17,20]])}))),gM.apply(this,arguments)}function mM(e,t){var i,r=(null==t||null===(i=t.gltf)||void 0===i?void 0:i.excludeExtensions)||{};return!(e in r&&!r[e])}var _M={accessors:"accessor",animations:"animation",buffers:"buffer",bufferViews:"bufferView",images:"image",materials:"material",meshes:"mesh",nodes:"node",samplers:"sampler",scenes:"scene",skins:"skin",textures:"texture"},yM={accessor:"accessors",animations:"animation",buffer:"buffers",bufferView:"bufferViews",image:"images",material:"materials",mesh:"meshes",node:"nodes",sampler:"samplers",scene:"scenes",skin:"skins",texture:"textures"},bM=function(){function e(){x(this,e),vb(this,"idToIndexMap",{animations:{},accessors:{},buffers:{},bufferViews:{},images:{},materials:{},meshes:{},nodes:{},samplers:{},scenes:{},skins:{},textures:{}}),vb(this,"json",void 0)}return C(e,[{key:"normalize",value:function(e,t){this.json=e.json;var i=e.json;switch(i.asset&&i.asset.version){case"2.0":return;case void 0:case"1.0":break;default:return void console.warn("glTF: Unknown version ".concat(i.asset.version))}if(!t.normalize)throw new Error("glTF v1 is not supported.");console.warn("Converting glTF v1 to glTF v2 format. This is experimental and may fail."),this._addAsset(i),this._convertTopLevelObjectsToArrays(i),function(e){var t,i=new XP(e),r=i.json,s=c(r.images||[]);try{for(s.s();!(t=s.n()).done;){var n=t.value,o=i.getObjectExtension(n,"KHR_binary_glTF");o&&Object.assign(n,o),i.removeObjectExtension(n,"KHR_binary_glTF")}}catch(e){s.e(e)}finally{s.f()}r.buffers&&r.buffers[0]&&delete r.buffers[0].uri,i.removeExtension("KHR_binary_glTF")}(e),this._convertObjectIdsToArrayIndices(i),this._updateObjects(i),this._updateMaterial(i)}},{key:"_addAsset",value:function(e){e.asset=e.asset||{},e.asset.version="2.0",e.asset.generator=e.asset.generator||"Normalized to glTF 2.0 by loaders.gl"}},{key:"_convertTopLevelObjectsToArrays",value:function(e){for(var t in _M)this._convertTopLevelObjectToArray(e,t)}},{key:"_convertTopLevelObjectToArray",value:function(e,t){var i=e[t];if(i&&!Array.isArray(i))for(var r in e[t]=[],i){var s=i[r];s.id=s.id||r;var n=e[t].length;e[t].push(s),this.idToIndexMap[t][r]=n}}},{key:"_convertObjectIdsToArrayIndices",value:function(e){for(var t in _M)this._convertIdsToIndices(e,t);"scene"in e&&(e.scene=this._convertIdToIndex(e.scene,"scene"));var i,r=c(e.textures);try{for(r.s();!(i=r.n()).done;){var s=i.value;this._convertTextureIds(s)}}catch(e){r.e(e)}finally{r.f()}var n,o=c(e.meshes);try{for(o.s();!(n=o.n()).done;){var a=n.value;this._convertMeshIds(a)}}catch(e){o.e(e)}finally{o.f()}var l,u=c(e.nodes);try{for(u.s();!(l=u.n()).done;){var A=l.value;this._convertNodeIds(A)}}catch(e){u.e(e)}finally{u.f()}var h,d=c(e.scenes);try{for(d.s();!(h=d.n()).done;){var p=h.value;this._convertSceneIds(p)}}catch(e){d.e(e)}finally{d.f()}}},{key:"_convertTextureIds",value:function(e){e.source&&(e.source=this._convertIdToIndex(e.source,"image"))}},{key:"_convertMeshIds",value:function(e){var t,i=c(e.primitives);try{for(i.s();!(t=i.n()).done;){var r=t.value,s=r.attributes,n=r.indices,o=r.material;for(var a in s)s[a]=this._convertIdToIndex(s[a],"accessor");n&&(r.indices=this._convertIdToIndex(n,"accessor")),o&&(r.material=this._convertIdToIndex(o,"material"))}}catch(e){i.e(e)}finally{i.f()}}},{key:"_convertNodeIds",value:function(e){var t=this;e.children&&(e.children=e.children.map((function(e){return t._convertIdToIndex(e,"node")}))),e.meshes&&(e.meshes=e.meshes.map((function(e){return t._convertIdToIndex(e,"mesh")})))}},{key:"_convertSceneIds",value:function(e){var t=this;e.nodes&&(e.nodes=e.nodes.map((function(e){return t._convertIdToIndex(e,"node")})))}},{key:"_convertIdsToIndices",value:function(e,t){e[t]||(console.warn("gltf v1: json doesn't contain attribute ".concat(t)),e[t]=[]);var i,r=c(e[t]);try{for(r.s();!(i=r.n()).done;){var s=i.value;for(var n in s){var o=s[n],a=this._convertIdToIndex(o,n);s[n]=a}}}catch(e){r.e(e)}finally{r.f()}}},{key:"_convertIdToIndex",value:function(e,t){var i=yM[t];if(i in this.idToIndexMap){var r=this.idToIndexMap[i][e];if(!Number.isFinite(r))throw new Error("gltf v1: failed to resolve ".concat(t," with id ").concat(e));return r}return e}},{key:"_updateObjects",value:function(e){var t,i=c(this.json.buffers);try{for(i.s();!(t=i.n()).done;){delete t.value.type}}catch(e){i.e(e)}finally{i.f()}}},{key:"_updateMaterial",value:function(e){var t,i=c(e.materials);try{var r=function(){var i=t.value;i.pbrMetallicRoughness={baseColorFactor:[1,1,1,1],metallicFactor:1,roughnessFactor:1};var r=(null===(s=i.values)||void 0===s?void 0:s.tex)||(null===(n=i.values)||void 0===n?void 0:n.texture2d_0),o=e.textures.findIndex((function(e){return e.id===r}));-1!==o&&(i.pbrMetallicRoughness.baseColorTexture={index:o})};for(i.s();!(t=i.n()).done;){var s,n;r()}}catch(e){i.e(e)}finally{i.f()}}}]),e}();function wM(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return(new bM).normalize(e,t)}var BM={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},xM={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},PM=10240,CM=10241,MM=10242,EM=10243,FM=10497,kM=9986,IM={magFilter:PM,minFilter:CM,wrapS:MM,wrapT:EM},DM=(o(e={},PM,9729),o(e,CM,kM),o(e,MM,FM),o(e,EM,FM),e);var SM=function(){function e(){x(this,e),vb(this,"baseUri",""),vb(this,"json",{}),vb(this,"buffers",[]),vb(this,"images",[])}return C(e,[{key:"postProcess",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e.json,r=e.buffers,s=void 0===r?[]:r,n=e.images,o=void 0===n?[]:n,a=e.baseUri,l=void 0===a?"":a;return TP(i),this.baseUri=l,this.json=i,this.buffers=s,this.images=o,this._resolveTree(this.json,t),this.json}},{key:"_resolveTree",value:function(e){var t=this;e.bufferViews&&(e.bufferViews=e.bufferViews.map((function(e,i){return t._resolveBufferView(e,i)}))),e.images&&(e.images=e.images.map((function(e,i){return t._resolveImage(e,i)}))),e.samplers&&(e.samplers=e.samplers.map((function(e,i){return t._resolveSampler(e,i)}))),e.textures&&(e.textures=e.textures.map((function(e,i){return t._resolveTexture(e,i)}))),e.accessors&&(e.accessors=e.accessors.map((function(e,i){return t._resolveAccessor(e,i)}))),e.materials&&(e.materials=e.materials.map((function(e,i){return t._resolveMaterial(e,i)}))),e.meshes&&(e.meshes=e.meshes.map((function(e,i){return t._resolveMesh(e,i)}))),e.nodes&&(e.nodes=e.nodes.map((function(e,i){return t._resolveNode(e,i)}))),e.skins&&(e.skins=e.skins.map((function(e,i){return t._resolveSkin(e,i)}))),e.scenes&&(e.scenes=e.scenes.map((function(e,i){return t._resolveScene(e,i)}))),void 0!==e.scene&&(e.scene=e.scenes[this.json.scene])}},{key:"getScene",value:function(e){return this._get("scenes",e)}},{key:"getNode",value:function(e){return this._get("nodes",e)}},{key:"getSkin",value:function(e){return this._get("skins",e)}},{key:"getMesh",value:function(e){return this._get("meshes",e)}},{key:"getMaterial",value:function(e){return this._get("materials",e)}},{key:"getAccessor",value:function(e){return this._get("accessors",e)}},{key:"getCamera",value:function(e){return null}},{key:"getTexture",value:function(e){return this._get("textures",e)}},{key:"getSampler",value:function(e){return this._get("samplers",e)}},{key:"getImage",value:function(e){return this._get("images",e)}},{key:"getBufferView",value:function(e){return this._get("bufferViews",e)}},{key:"getBuffer",value:function(e){return this._get("buffers",e)}},{key:"_get",value:function(e,t){if("object"===B(t))return t;var i=this.json[e]&&this.json[e][t];return i||console.warn("glTF file error: Could not find ".concat(e,"[").concat(t,"]")),i}},{key:"_resolveScene",value:function(e,t){var i=this;return e.id=e.id||"scene-".concat(t),e.nodes=(e.nodes||[]).map((function(e){return i.getNode(e)})),e}},{key:"_resolveNode",value:function(e,t){var i=this;return e.id=e.id||"node-".concat(t),e.children&&(e.children=e.children.map((function(e){return i.getNode(e)}))),void 0!==e.mesh?e.mesh=this.getMesh(e.mesh):void 0!==e.meshes&&e.meshes.length&&(e.mesh=e.meshes.reduce((function(e,t){var r=i.getMesh(t);return e.id=r.id,e.primitives=e.primitives.concat(r.primitives),e}),{primitives:[]})),void 0!==e.camera&&(e.camera=this.getCamera(e.camera)),void 0!==e.skin&&(e.skin=this.getSkin(e.skin)),e}},{key:"_resolveSkin",value:function(e,t){return e.id=e.id||"skin-".concat(t),e.inverseBindMatrices=this.getAccessor(e.inverseBindMatrices),e}},{key:"_resolveMesh",value:function(e,t){var i=this;return e.id=e.id||"mesh-".concat(t),e.primitives&&(e.primitives=e.primitives.map((function(e){var t=(e=n({},e)).attributes;for(var r in e.attributes={},t)e.attributes[r]=i.getAccessor(t[r]);return void 0!==e.indices&&(e.indices=i.getAccessor(e.indices)),void 0!==e.material&&(e.material=i.getMaterial(e.material)),e}))),e}},{key:"_resolveMaterial",value:function(e,t){if(e.id=e.id||"material-".concat(t),e.normalTexture&&(e.normalTexture=n({},e.normalTexture),e.normalTexture.texture=this.getTexture(e.normalTexture.index)),e.occlusionTexture&&(e.occlustionTexture=n({},e.occlustionTexture),e.occlusionTexture.texture=this.getTexture(e.occlusionTexture.index)),e.emissiveTexture&&(e.emmisiveTexture=n({},e.emmisiveTexture),e.emissiveTexture.texture=this.getTexture(e.emissiveTexture.index)),e.emissiveFactor||(e.emissiveFactor=e.emmisiveTexture?[1,1,1]:[0,0,0]),e.pbrMetallicRoughness){e.pbrMetallicRoughness=n({},e.pbrMetallicRoughness);var i=e.pbrMetallicRoughness;i.baseColorTexture&&(i.baseColorTexture=n({},i.baseColorTexture),i.baseColorTexture.texture=this.getTexture(i.baseColorTexture.index)),i.metallicRoughnessTexture&&(i.metallicRoughnessTexture=n({},i.metallicRoughnessTexture),i.metallicRoughnessTexture.texture=this.getTexture(i.metallicRoughnessTexture.index))}return e}},{key:"_resolveAccessor",value:function(e,t){var i,r;if(e.id=e.id||"accessor-".concat(t),void 0!==e.bufferView&&(e.bufferView=this.getBufferView(e.bufferView)),e.bytesPerComponent=(i=e.componentType,xM[i]),e.components=(r=e.type,BM[r]),e.bytesPerElement=e.bytesPerComponent*e.components,e.bufferView){var s=e.bufferView.buffer,n=zP(e,e.bufferView),o=n.ArrayType,a=n.byteLength,l=(e.bufferView.byteOffset||0)+(e.byteOffset||0)+s.byteOffset,u=s.arrayBuffer.slice(l,l+a);e.bufferView.byteStride&&(u=this._getValueFromInterleavedBuffer(s,l,e.bufferView.byteStride,e.bytesPerElement,e.count)),e.value=new o(u)}return e}},{key:"_getValueFromInterleavedBuffer",value:function(e,t,i,r,s){for(var n=new Uint8Array(s*r),o=0;o1&&void 0!==arguments[1]?arguments[1]:0;return"".concat(String.fromCharCode(e.getUint8(t+0))).concat(String.fromCharCode(e.getUint8(t+1))).concat(String.fromCharCode(e.getUint8(t+2))).concat(String.fromCharCode(e.getUint8(t+3)))}function UM(e,t,i){ob(e.header.byteLength>20);var r=t.getUint32(i+0,LM),s=t.getUint32(i+4,LM);return i+=8,ob(0===s),NM(e,t,i,r),i+=r,i+=QM(e,t,i,e.header.byteLength)}function OM(e,t,i,r){return ob(e.header.byteLength>20),function(e,t,i,r){for(;i+8<=e.header.byteLength;){var s=t.getUint32(i+0,LM),n=t.getUint32(i+4,LM);switch(i+=8,n){case 1313821514:NM(e,t,i,s);break;case 5130562:QM(e,t,i,s);break;case 0:r.strict||NM(e,t,i,s);break;case 1:r.strict||QM(e,t,i,s)}i+=Jb(s,4)}}(e,t,i,r),i+e.header.byteLength}function NM(e,t,i,r){var s=new Uint8Array(t.buffer,i,r),n=new TextDecoder("utf8").decode(s);return e.json=JSON.parse(n),Jb(r,4)}function QM(e,t,i,r){return e.header.hasBinChunk=!0,e.binChunks.push({byteOffset:i,byteLength:r,arrayBuffer:t.buffer}),Jb(r,4)}function VM(e,t){return HM.apply(this,arguments)}function HM(){return HM=u(a().mark((function e(t,i){var r,s,n,o,l,u,A,c,h,d,p=arguments;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=p.length>2&&void 0!==p[2]?p[2]:0,s=p.length>3?p[3]:void 0,n=p.length>4?p[4]:void 0,jM(t,i,r,s),wM(t,{normalize:null==s||null===(o=s.gltf)||void 0===o?void 0:o.normalize}),fM(t,s,n),c=[],null==s||null===(l=s.gltf)||void 0===l||!l.loadBuffers||!t.json.buffers){e.next=10;break}return e.next=10,GM(t,s,n);case 10:return null!=s&&null!==(u=s.gltf)&&void 0!==u&&u.loadImages&&(h=WM(t,s,n),c.push(h)),d=vM(t,s,n),c.push(d),e.next=15,Promise.all(c);case 15:return e.abrupt("return",null!=s&&null!==(A=s.gltf)&&void 0!==A&&A.postProcess?TM(t,s):t);case 16:case"end":return e.stop()}}),e)}))),HM.apply(this,arguments)}function jM(e,t,i,r){(r.uri&&(e.baseUri=r.uri),t instanceof ArrayBuffer&&!function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=new DataView(e),s=i.magic,n=void 0===s?1735152710:s,o=r.getUint32(t,!1);return o===n||1735152710===o}(t,i,r))&&(t=(new TextDecoder).decode(t));if("string"==typeof t)e.json=zb(t);else if(t instanceof ArrayBuffer){var s={};i=function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,r=new DataView(t),s=RM(r,i+0),n=r.getUint32(i+4,LM),o=r.getUint32(i+8,LM);switch(Object.assign(e,{header:{byteOffset:i,byteLength:o,hasBinChunk:!1},type:s,version:n,json:{},binChunks:[]}),i+=12,e.version){case 1:return UM(e,r,i);case 2:return OM(e,r,i,{});default:throw new Error("Invalid GLB version ".concat(e.version,". Only supports v1 and v2."))}}(s,t,i,r.glb),TP("glTF"===s.type,"Invalid GLB magic string ".concat(s.type)),e._glb=s,e.json=s.json}else TP(!1,"GLTF: must be ArrayBuffer or string");var n=e.json.buffers||[];if(e.buffers=new Array(n.length).fill(null),e._glb&&e._glb.header.hasBinChunk){var o=e._glb.binChunks;e.buffers[0]={arrayBuffer:o[0].arrayBuffer,byteOffset:o[0].byteOffset,byteLength:o[0].byteLength}}var a=e.json.images||[];e.images=new Array(a.length).fill({})}function GM(e,t,i){return zM.apply(this,arguments)}function zM(){return(zM=u(a().mark((function e(t,i,r){var s,n,o,l,u,A,c,h;return a().wrap((function(e){for(;;)switch(e.prev=e.next){case 0:s=t.json.buffers||[],n=0;case 2:if(!(n1&&void 0!==u[1]?u[1]:{},r=u.length>2?u[2]:void 0,(i=n(n({},ZM.options),i)).gltf=n(n({},ZM.options.gltf),i.gltf),s=i.byteOffset,o=void 0===s?0:s,l={},e.next=8,VM(l,t,o,i,r);case 8:return e.abrupt("return",e.sent);case 9:case"end":return e.stop()}}),e)}))),qM.apply(this,arguments)}var $M=function(){function e(t){x(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n,o){!function(e,t,i,r,s,n,o){var a=e.viewer.scene.canvas.spinner;a.processes++,"glb"===t.split(".").pop()?e.dataSource.getGLB(t,(function(o){r.basePath=tE(t),iE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)})):e.dataSource.getGLTF(t,(function(o){r.basePath=tE(t),iE(e,t,o,i,r,s,n),a.processes--}),(function(e){a.processes--,o(e)}))}(e,t,i,r=r||{},s,(function(){_e.scheduleTask((function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1)})),n&&n()}),(function(t){e.error(t),o&&o(t),s.fire("error",t)}))}},{key:"parse",value:function(e,t,i,r,s,n,o){iE(e,"",t,i,r=r||{},s,(function(){s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1),n&&n()}))}}]),e}();function eE(e){for(var t={},i={},r=e.metaObjects||[],s={},n=0,o=r.length;n0)for(var A=0;A0){null==y&&e.log("Warning: 'name' properties not found on glTF scene nodes - will randomly-generate object IDs in XKT");var b=y;if(e.metaModelCorrections){var w=e.metaModelCorrections.eachChildRoot[b];if(w){var B=e.metaModelCorrections.eachRootStats[w.id];B.countChildren++,B.countChildren>=B.numChildren&&(n.createEntity({id:w.id,meshIds:aE,isObject:!0}),aE.length=0)}else{e.metaModelCorrections.metaObjectsMap[b]&&(n.createEntity({id:b,meshIds:aE,isObject:!0}),aE.length=0)}}else n.createEntity({id:b,meshIds:aE,isObject:!0}),aE.length=0}}}function uE(e,t){e.plugin.error(t)}var AE={DEFAULT:{}},cE=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"GLTFLoader",e,s))._sceneModelLoader=new $M(b(r),s),r.dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Sh}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0,dtxEnabled:t.dtxEnabled})),r=i.id;if(!t.src&&!t.gltf)return this.error("load() param expected: src or gltf"),i;if(t.metaModelSrc||t.metaModelJSON){var s=t.objectDefaults||this._objectDefaults||AE,n=function(n){var o;if(e.viewer.metaScene.createMetaModel(r,n,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes}),e.viewer.scene.canvas.spinner.processes--,t.includeTypes){o={};for(var a=0,l=t.includeTypes.length;a2&&void 0!==arguments[2]?arguments[2]:{},r="lightgrey",s=i.hoverColor||"rgba(0,0,0,0.4)",n=i.textColor||"black",o=500,a=o+o/3,l=a/24,u=[{boundary:[6,6,6,6],color:i.frontColor||i.color||"#55FF55"},{boundary:[18,6,6,6],color:i.backColor||i.color||"#55FF55"},{boundary:[12,6,6,6],color:i.rightColor||i.color||"#FF5555"},{boundary:[0,6,6,6],color:i.leftColor||i.color||"#FF5555"},{boundary:[6,0,6,6],color:i.topColor||i.color||"#7777FF"},{boundary:[6,12,6,6],color:i.bottomColor||i.color||"#7777FF"}],A=[{label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}];i.frontColor||i.color,i.backColor||i.color,i.rightColor||i.color,i.leftColor||i.color,i.topColor||i.color,i.bottomColor||i.color;for(var c=[{yUp:"",label:"NavCube.front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"NavCube.back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"NavCube.right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"NavCube.left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"NavCube.top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"NavCube.bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-.7071,-.7071],up:[0,.7071,-.7071]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-.7071,.7071],up:[0,.7071,.7071]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[.5,.7071,-.5],up:[-.5,.7071,.5]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[.5,.7071,.5],up:[-.5,.7071,-.5]},{boundaries:[[5,5,2,2]],dir:[.5,-.7071,-.5],up:[.5,.7071,-.5]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-.5,.7071,.5],up:[.5,.7071,-.5]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-.5,-.7071,.5],up:[-.5,.7071,.5]},{boundaries:[[11,11,2,2]],dir:[-.5,.7071,-.5],up:[.5,.7071,.5]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[.5,-.7071,.5],up:[.5,.7071,.5]},{boundaries:[[11,5,2,2]],dir:[-.5,-.7071,-.5],up:[-.5,.7071,-.5]}],h=0,d=A.length;h=c[0]*l&&t<=(c[0]+c[2])*l&&i>=c[1]*l&&i<=(c[1]+c[3])*l)return r}return-1},this.setAreaHighlighted=function(e,t){var i=v[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,y()},this.getAreaDir=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=v[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)}}var dE=$.vec3(),pE=$.vec3();$.mat4();var fE=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),r=t.call(this,"NavCube",e,s),e.navCube=b(r);var n=!0;try{r._navCubeScene=new $i(e,{canvasId:s.canvasId,canvasElement:s.canvasElement,transparent:!0}),r._navCubeCanvas=r._navCubeScene.canvas.canvas,r._navCubeScene.input.keyboardEnabled=!1}catch(e){return r.error(e),y(r)}var o=r._navCubeScene;o.clearLights(),new bi(o,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(o,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(o,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),r._navCubeCamera=o.camera,r._navCubeCamera.ortho.scale=7,r._navCubeCamera.ortho.near=.1,r._navCubeCamera.ortho.far=2e3,o.edgeMaterial.edgeColor=[.2,.2,.2],o.edgeMaterial.edgeAlpha=.6,r._zUp=Boolean(e.camera.zUp);var a=b(r);r.setIsProjectNorth(s.isProjectNorth),r.setProjectNorthOffsetAngle(s.projectNorthOffsetAngle);var l,u=(l=$.mat4(),function(e,t,i){return $.identityMat4(l),$.rotationMat4v(e*a._projectNorthOffsetAngle*$.DEGTORAD,[0,1,0],l),$.transformVec3(l,t,i)});r._synchCamera=function(){var t=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),i=$.vec3(),r=$.vec3(),s=$.vec3();return function(){var n=e.camera.eye,o=e.camera.look,l=e.camera.up;i=$.mulVec3Scalar($.normalizeVec3($.subVec3(n,o,i)),5),a._isProjectNorth&&a._projectNorthOffsetAngle&&(i=u(-1,i,dE),l=u(-1,l,pE)),a._zUp?($.transformVec3(t,i,r),$.transformVec3(t,l,s),a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=$.transformVec3(t,i,r),a._navCubeCamera.up=$.transformPoint3(t,l,s)):(a._navCubeCamera.look=[0,0,0],a._navCubeCamera.eye=i,a._navCubeCamera.up=l)}}(),r._cubeTextureCanvas=new hE(e,o,s),r._cubeSampler=new On(o,{image:r._cubeTextureCanvas.getImage(),flipY:!0,wrapS:1001,wrapT:1001}),r._cubeMesh=new nn(o,{geometry:new Ti(o,{primitive:"triangles",normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),material:new Ni(o,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:r._cubeSampler,emissiveMap:r._cubeSampler}),visible:!!n,edges:!0}),r._shadow=!1===s.shadowVisible?null:new nn(o,{geometry:new Ti(o,an({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new Ni(o,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!!n,pickable:!1,backfaces:!1}),r._onCameraMatrix=e.camera.on("matrix",r._synchCamera),r._onCameraWorldAxis=e.camera.on("worldAxis",(function(){e.camera.zUp?(r._zUp=!0,r._cubeTextureCanvas.setZUp(),r._repaint(),r._synchCamera()):e.camera.yUp&&(r._zUp=!1,r._cubeTextureCanvas.setYUp(),r._repaint(),r._synchCamera())})),r._onCameraFOV=e.camera.perspective.on("fov",(function(e){r._synchProjection&&(r._navCubeCamera.perspective.fov=e)})),r._onCameraProjection=e.camera.on("projection",(function(e){r._synchProjection&&(r._navCubeCamera.projection="ortho"===e||"perspective"===e?e:"perspective")}));var A=-1;function c(t,i){var r=(t-d)*-_,s=(i-p)*-_;e.camera.orbitYaw(r),e.camera.orbitPitch(-s),d=t,p=i}function h(e){var t=[0,0];if(e){for(var i=e.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-r,t[1]=e.pageY-s}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var d,p,f=null,v=null,g=!1,m=!1,_=.5;a._navCubeCanvas.addEventListener("mouseenter",a._onMouseEnter=function(e){m=!0}),a._navCubeCanvas.addEventListener("mouseleave",a._onMouseLeave=function(e){m=!1}),a._navCubeCanvas.addEventListener("mousedown",a._onMouseDown=function(e){if(1===e.which){f=e.x,v=e.y,d=e.clientX,p=e.clientY;var t=h(e),i=o.pick({canvasPos:t});g=!!i}}),document.addEventListener("mouseup",a._onMouseUp=function(e){if(1===e.which&&(g=!1,null!==f)){var t=h(e),i=o.pick({canvasPos:t,pickSurface:!0});if(i&&i.uv){var r=a._cubeTextureCanvas.getArea(i.uv);if(r>=0&&(document.body.style.cursor="pointer",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),r>=0)){if(a._cubeTextureCanvas.setAreaHighlighted(r,!0),A=r,a._repaint(),e.xf+3||e.yv+3)return;var s=a._cubeTextureCanvas.getAreaDir(r);if(s){var n=a._cubeTextureCanvas.getAreaUp(r);a._isProjectNorth&&a._projectNorthOffsetAngle&&(s=u(1,s,dE),n=u(1,n,pE)),w(s,n,(function(){A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),document.body.style.cursor="pointer",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),r>=0&&(a._cubeTextureCanvas.setAreaHighlighted(r,!1),A=-1,a._repaint())}))}}}}}),document.addEventListener("mousemove",a._onMouseMove=function(e){if(A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1),1!==e.buttons||g){if(g){var t=e.clientX,i=e.clientY;return document.body.style.cursor="move",void c(t,i)}if(m){var r=h(e),s=o.pick({canvasPos:r,pickSurface:!0});if(s){if(s.uv){document.body.style.cursor="pointer";var n=a._cubeTextureCanvas.getArea(s.uv);if(n===A)return;A>=0&&a._cubeTextureCanvas.setAreaHighlighted(A,!1),n>=0&&(a._cubeTextureCanvas.setAreaHighlighted(n,!0),a._repaint(),A=n)}}else document.body.style.cursor="default",A>=0&&(a._cubeTextureCanvas.setAreaHighlighted(A,!1),a._repaint(),A=-1)}}});var w=function(){var t=$.vec3();return function(i,r,s){var n=a._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,o=$.getAABB3Diag(n);$.getAABB3Center(n,t);var l=Math.abs(o/Math.tan(a._cameraFitFOV*$.DEGTORAD));e.cameraControl.pivotPos=t,a._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV,duration:a._cameraFlyDuration},s):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.1*o,fitFOV:a._cameraFitFOV},s)}}();return r._onUpdated=e.localeService.on("updated",(function(){r._cubeTextureCanvas.clear(),r._repaint()})),r.setVisible(s.visible),r.setCameraFitFOV(s.cameraFitFOV),r.setCameraFly(s.cameraFly),r.setCameraFlyDuration(s.cameraFlyDuration),r.setFitVisible(s.fitVisible),r.setSynchProjection(s.synchProjection),r}return C(i,[{key:"send",value:function(e,t){if("language"===e)this._cubeTextureCanvas.clear(),this._repaint()}},{key:"_repaint",value:function(){var e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow&&(this._shadow.visible=e),this._navCubeCanvas.style.visibility=e?"visible":"hidden")}},{key:"getVisible",value:function(){return!!this._navCubeCanvas&&this._cubeMesh.visible}},{key:"setFitVisible",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._fitVisible=e}},{key:"getFitVisible",value:function(){return this._fitVisible}},{key:"setCameraFly",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._cameraFly=e}},{key:"getCameraFly",value:function(){return this._cameraFly}},{key:"setCameraFitFOV",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:45;this._cameraFitFOV=e}},{key:"getCameraFitFOV",value:function(){return this._cameraFitFOV}},{key:"setCameraFlyDuration",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.5;this._cameraFlyDuration=e}},{key:"getCameraFlyDuration",value:function(){return this._cameraFlyDuration}},{key:"setSynchProjection",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._synchProjection=e}},{key:"getSynchProjection",value:function(){return this._synchProjection}},{key:"setIsProjectNorth",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this._isProjectNorth=e}},{key:"getIsProjectNorth",value:function(){return this._isProjectNorth}},{key:"setProjectNorthOffsetAngle",value:function(e){this._projectNorthOffsetAngle=e}},{key:"getProjectNorthOffsetAngle",value:function(){return this._projectNorthOffsetAngle}},{key:"destroy",value:function(){this._navCubeCanvas&&(this.viewer.localeService.off(this._onUpdated),this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,f(w(i.prototype),"destroy",this).call(this)}}]),i}(),vE=$.vec3(),gE=function(){function e(){x(this,e)}return C(e,[{key:"load",value:function(e,t){var i=e.scene.canvas.spinner;i.processes++,mE(e,t,(function(t){yE(e,t,(function(){BE(e,t),i.processes--,_e.scheduleTask((function(){e.fire("loaded",!0,!1)}))}))}))}},{key:"parse",value:function(e,t,i,r){if(t){var s=_E(e,t,null);i&&wE(e,i,r),BE(e,s),e.src=null,e.fire("loaded",!0,!1)}else this.warn("load() param expected: objText")}}]),e}(),mE=function(e,t,i){xE(t,(function(r){var s=_E(e,r,t);i(s)}),(function(t){e.error(t)}))},_E=function(){var e={vertex_pattern:/^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,normal_pattern:/^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,uv_pattern:/^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,face_vertex:/^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,face_vertex_uv:/^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,face_vertex_uv_normal:/^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,face_vertex_normal:/^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,object_pattern:/^[og]\s*(.+)?/,smoothing_pattern:/^s\s+(\d+|on|off)/,material_library_pattern:/^mtllib /,material_use_pattern:/^usemtl /};return function(r,s,n){var o={src:n=n||"",basePath:t(n),objects:[],object:{},positions:[],normals:[],uv:[],materialLibraries:{}};i(o,"",!1),-1!==s.indexOf("\r\n")&&(s=s.replace("\r\n","\n"));for(var a=s.split("\n"),l="",u="",A="",d=[],p="function"==typeof"".trimLeft,f=0,v=a.length;f=0?i-1:i+t/3)}function s(e,t){var i=parseInt(e,10);return 3*(i>=0?i-1:i+t/3)}function n(e,t){var i=parseInt(e,10);return 2*(i>=0?i-1:i+t/2)}function o(e,t,i,r){var s=e.positions,n=e.object.geometry.positions;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function a(e,t){var i=e.positions,r=e.object.geometry.positions;r.push(i[t+0]),r.push(i[t+1]),r.push(i[t+2])}function l(e,t,i,r){var s=e.normals,n=e.object.geometry.normals;n.push(s[t+0]),n.push(s[t+1]),n.push(s[t+2]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[i+2]),n.push(s[r+0]),n.push(s[r+1]),n.push(s[r+2])}function u(e,t,i,r){var s=e.uv,n=e.object.geometry.uv;n.push(s[t+0]),n.push(s[t+1]),n.push(s[i+0]),n.push(s[i+1]),n.push(s[r+0]),n.push(s[r+1])}function A(e,t){var i=e.uv,r=e.object.geometry.uv;r.push(i[t+0]),r.push(i[t+1])}function c(e,t,i,a,A,c,h,d,p,f,v,g,m){var _,y=e.positions.length,b=r(t,y),w=r(i,y),B=r(a,y);if(void 0===A?o(e,b,w,B):(o(e,b,w,_=r(A,y)),o(e,w,B,_)),void 0!==c){var x=e.uv.length;b=n(c,x),w=n(h,x),B=n(d,x),void 0===A?u(e,b,w,B):(u(e,b,w,_=n(p,x)),u(e,w,B,_))}if(void 0!==f){var P=e.normals.length;b=s(f,P),w=f===v?b:s(v,P),B=f===g?b:s(g,P),void 0===A?l(e,b,w,B):(l(e,b,w,_=s(m,P)),l(e,w,B,_))}}function h(e,t,i){e.object.geometry.type="Line";for(var s=e.positions.length,o=e.uv.length,l=0,u=t.length;l=0?o.substring(0,a):o).toLowerCase(),u=(u=a>=0?o.substring(a+1):"").trim(),l.toLowerCase()){case"newmtl":i(e,h),h={id:u},d=!0;break;case"ka":h.ambient=r(u);break;case"kd":h.diffuse=r(u);break;case"ks":h.specular=r(u);break;case"map_kd":h.diffuseMap||(h.diffuseMap=t(e,n,u,"sRGB"));break;case"map_ks":h.specularMap||(h.specularMap=t(e,n,u,"linear"));break;case"map_bump":case"bump":h.normalMap||(h.normalMap=t(e,n,u));break;case"ns":h.shininess=parseFloat(u);break;case"d":(A=parseFloat(u))<1&&(h.alpha=A,h.alphaMode="blend");break;case"tr":(A=parseFloat(u))>0&&(h.alpha=1-A,h.alphaMode="blend")}d&&i(e,h)};function t(e,t,i,r){var s={},n=i.split(/\s+/),o=n.indexOf("-bm");return o>=0&&n.splice(o,2),(o=n.indexOf("-s"))>=0&&(s.scale=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),(o=n.indexOf("-o"))>=0&&(s.translate=[parseFloat(n[o+1]),parseFloat(n[o+2])],n.splice(o,4)),s.src=t+n.join(" ").trim(),s.flipY=!0,s.encoding=r||"linear",new On(e,s).id}function i(e,t){new Ni(e,t)}function r(t){var i=t.split(e,3);return[parseFloat(i[0]),parseFloat(i[1]),parseFloat(i[2])]}}();function BE(e,t){for(var i=0,r=t.objects.length;i0&&(o.normals=n.normals),n.uv.length>0&&(o.uv=n.uv);for(var a=new Array(o.positions.length/3),l=0;l0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new wn(this.viewer.scene,le.apply(t,{isModel:!0})),r=i.id,s=t.src;if(!s)return this.error("load() param expected: src"),i;if(t.metaModelSrc){var n=t.metaModelSrc;le.loadJSON(n,(function(n){e.viewer.metaScene.createMetaModel(r,n),e._sceneGraphLoader.load(i,s,t)}),(function(t){e.error("load(): Failed to load model modelMetadata for model '".concat(r," from '").concat(n,"' - ").concat(t))}))}else this._sceneGraphLoader.load(i,s,t);return i.once("destroyed",(function(){e.viewer.metaScene.destroyMetaModel(r)})),i}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),CE=new Float64Array([0,0,1]),ME=new Float64Array(4),EE=function(){function e(t){x(this,e),this.id=null,this._viewer=t.viewer,this._visible=!1,this._pos=$.vec3(),this._origin=$.vec3(),this._rtcPos=$.vec3(),this._baseDir=$.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),Re(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=$.vec3PairToQuaternion(CE,e,ME)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new wn(t,{position:[0,0,0],scale:[5,5,5],isObject:!1});var r,s,n=this._rootNode,o={arrowHead:new Ti(n,an({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ti(n,an({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Ti(n,an({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Ti(n,Jn({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Ti(n,Jn({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Ti(n,Jn({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Ti(n,an({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Ti(n,an({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},a={pickable:new Ni(n,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new Ni(n,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Vi(n,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new Ni(n,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new Vi(n,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new Ni(n,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new Vi(n,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new Ni(n,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new Vi(n,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new Vi(n,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:n.addChild(new nn(n,{geometry:new Ti(n,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new Ni(n,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new Vi(n,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1],isObject:!1}),e),planeFrame:n.addChild(new nn(n,{geometry:new Ti(n,Jn({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(n,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new Vi(n,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45],isObject:!1}),e),xCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.red,matrix:(r=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),s=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4()),$.mulMat4(s,r,$.identityMat4())),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,matrix:function(){var e=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),t=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,-.07,-.8,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(0*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,-.8,-.07,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),yCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(.07,0,-.8,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(.8,0,-.07,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurve:n.addChild(new nn(n,{geometry:o.curve,material:a.blue,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveHandle:n.addChild(new nn(n,{geometry:o.curveHandle,material:a.pickable,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveCurveArrow1:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(.8,-.07,0,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4());return $.mulMat4(e,t,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zCurveArrow2:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(.05,-.8,0,$.identityMat4()),t=$.scaleMat4v([.6,.6,.6],$.identityMat4()),i=$.rotationMat4v(90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4($.mulMat4(e,t,$.identityMat4()),i,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),center:n.addChild(new nn(n,{geometry:new Ti(n,ln({radius:.05})),material:a.center,pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.red,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxis:n.addChild(new nn(n,{geometry:o.axis,material:a.red,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),xAxisHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.green,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2,isObject:!1}),e),yShaft:n.addChild(new nn(n,{geometry:o.axis,material:a.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yShaftHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHead,material:a.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrowHandle:n.addChild(new nn(n,{geometry:o.arrowHeadHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zShaft:n.addChild(new nn(n,{geometry:o.axis,material:a.blue,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1,isObject:!1}),e),zAxisHandle:n.addChild(new nn(n,{geometry:o.axisHandle,material:a.pickable,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1,isObject:!1}),e)},this._affordanceMeshes={planeFrame:n.addChild(new nn(n,{geometry:new Ti(n,Jn({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(n,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Vi(n,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45],isObject:!1}),e),xHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.red,highlighted:!0,highlightMaterial:a.highlightRed,matrix:function(){var e=$.rotationMat4v(90*$.DEGTORAD,[0,1,0],$.identityMat4()),t=$.rotationMat4v(270*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.green,highlighted:!0,highlightMaterial:a.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zHoop:n.addChild(new nn(n,{geometry:o.hoop,material:a.blue,highlighted:!0,highlightMaterial:a.highlightBlue,matrix:$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1,isObject:!1}),e),xAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.red,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[0,0,1],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),yAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.green,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(180*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e),zAxisArrow:n.addChild(new nn(n,{geometry:o.arrowHeadBig,material:a.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1,isObject:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this,i=!1,r=-1,s=0,n=1,o=2,a=3,l=4,u=5,A=this._rootNode,c=null,h=null,d=$.vec2(),p=$.vec3([1,0,0]),f=$.vec3([0,1,0]),v=$.vec3([0,0,1]),g=this._viewer.scene.canvas.canvas,m=this._viewer.camera,_=this._viewer.scene,y=$.vec3([0,0,0]),b=-1;this._onCameraViewMatrix=_.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=_.camera.on("projMatrix",(function(){})),this._onSceneTick=_.on("tick",(function(){var t=Math.abs($.lenVec3($.subVec3(_.camera.eye,e._pos,y)));if(t!==b&&"perspective"===m.projection){var i=.07*(Math.tan(m.perspective.fov*$.DEGTORAD)*t);A.scale=[i,i,i],b=t}if("ortho"===m.projection){var r=m.ortho.scale/10;A.scale=[r,r,r],b=t}}));var w,B,x,P,C,M=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),E=function(){var e=$.mat4();return function(i,r){return $.quaternionToMat4(t._rootNode.quaternion,e),$.transformVec3(e,i,r),$.normalizeVec3(r),r}}(),F=(w=$.vec3(),function(e){var t=Math.abs(e[0]);return t>Math.abs(e[1])&&t>Math.abs(e[2])?$.cross3Vec3(e,[0,1,0],w):$.cross3Vec3(e,[1,0,0],w),$.cross3Vec3(w,e,w),$.normalizeVec3(w),w}),k=(B=$.vec3(),x=$.vec3(),P=$.vec4(),function(e,i,r){E(e,P);var s=F(P,i,r);D(i,s,B),D(r,s,x),$.subVec3(x,B);var n=$.dotVec3(x,P);t._pos[0]+=P[0]*n,t._pos[1]+=P[1]*n,t._pos[2]+=P[2]*n,t._rootNode.position=t._pos,t._sectionPlane&&(t._sectionPlane.pos=t._pos)}),I=function(){var e=$.vec4(),i=$.vec4(),r=$.vec4(),s=$.vec4();return function(n,o,a){if(E(n,s),!(D(o,s,e)&&D(a,s,i))){var l=F(s,o,a);D(o,l,e,1),D(a,l,i,1);var u=$.dotVec3(e,s);e[0]-=u*s[0],e[1]-=u*s[1],e[2]-=u*s[2],u=$.dotVec3(i,s),i[0]-=u*s[0],i[1]-=u*s[1],i[2]-=u*s[2]}$.normalizeVec3(e),$.normalizeVec3(i),u=$.dotVec3(e,i),u=$.clamp(u,-1,1);var A=Math.acos(u)*$.RADTODEG;$.cross3Vec3(e,i,r),$.dotVec3(r,s)<0&&(A=-A),t._rootNode.rotate(n,A),S()}}(),D=function(){var e=$.vec4([0,0,0,1]),i=$.mat4();return function(r,s,n,o){o=o||0,e[0]=r[0]/g.width*2-1,e[1]=-(r[1]/g.height*2-1),e[2]=0,e[3]=1,$.mulMat4(m.projMatrix,m.viewMatrix,i),$.inverseMat4(i),$.transformVec4(i,e,e),$.mulVec4Scalar(e,1/e[3]);var a=m.eye;$.subVec4(e,a,e);var l=t._sectionPlane.pos,u=-$.dotVec3(l,s)-o,A=$.dotVec3(s,e);if(Math.abs(A)>.005){var c=-($.dotVec3(s,a)+u)/A;return $.mulVec3Scalar(e,c,n),$.addVec3(n,a),$.subVec3(n,l,n),!0}return!1}}(),S=function(){var e=$.vec3(),i=$.mat4();return function(){t.sectionPlane&&($.quaternionToMat4(A.quaternion,i),$.transformVec3(i,[0,0,1],e),t._setSectionPlaneDir(e))}}(),T=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(function(t){if(e._visible&&!T){var A;switch(i=!1,C&&(C.visible=!1),t.entity.id){case e._displayMeshes.xAxisArrowHandle.id:case e._displayMeshes.xAxisHandle.id:A=e._affordanceMeshes.xAxisArrow,c=s;break;case e._displayMeshes.yAxisArrowHandle.id:case e._displayMeshes.yShaftHandle.id:A=e._affordanceMeshes.yAxisArrow,c=n;break;case e._displayMeshes.zAxisArrowHandle.id:case e._displayMeshes.zAxisHandle.id:A=e._affordanceMeshes.zAxisArrow,c=o;break;case e._displayMeshes.xCurveHandle.id:A=e._affordanceMeshes.xHoop,c=a;break;case e._displayMeshes.yCurveHandle.id:A=e._affordanceMeshes.yHoop,c=l;break;case e._displayMeshes.zCurveHandle.id:A=e._affordanceMeshes.zHoop,c=u;break;default:return void(c=r)}A&&(A.visible=!0),C=A,i=!0}})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOutEntity",(function(t){e._visible&&(C&&(C.visible=!1),C=null,c=r)})),g.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&i&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){T=!0;var r=M(t);h=c,d[0]=r[0],d[1]=r[1]}}),g.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&T){var i=M(t),r=i[0],A=i[1];switch(h){case s:k(p,d,i);break;case n:k(f,d,i);break;case o:k(v,d,i);break;case a:I(p,d,i);break;case l:I(f,d,i);break;case u:I(v,d,i)}d[0]=r,d[1]=A}}),g.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,T&&(t.which,T=!1,i=!1))}),g.addEventListener("wheel",this._canvasWheelListener=function(t){if(e._visible)Math.max(-1,Math.min(1,40*-t.deltaY))})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix),s.off(this._onCameraControlHover),s.off(this._onCameraControlHoverLeave)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),FE=function(){function e(t,i,r){var s=this;x(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new nn(i,{id:r.id,geometry:new Ti(i,Li({xSize:.5,ySize:.5,zSize:.001})),material:new Ni(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ji(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Vi(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Vi(i,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});var n=$.vec3([0,0,0]),o=$.vec3(),a=$.vec3([0,0,1]),l=$.vec4(4),u=$.vec3(),A=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];$.subVec3(e,s._sectionPlane.pos,n);var i=-$.dotVec3(t,n);$.normalizeVec3(t),$.mulVec3Scalar(t,i,o);var r=$.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",A),this._onSectionPlaneDir=this._sectionPlane.on("dir",A),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),kE=function(){function e(t,i){var r=this;if(x(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new $i(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new bi(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;var s=this._scene.camera,n=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),o=$.vec3(),a=$.vec3(),l=$.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;$.mulVec3Scalar($.normalizeVec3($.subVec3(e,t,o)),7),r._zUp?($.transformVec3(n,o,a),$.transformVec3(n,i,l),s.look=[0,0,0],s.eye=$.transformVec3(n,o,a),s.up=$.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new FE(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}]),e}(),IE=$.AABB3(),DE=$.vec3(),SE=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,"SectionPlanes",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new kE(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;IE.set(r.viewer.scene.aabb),$.getAABB3Center(IE,DE),IE[0]+=t[0]-DE[0],IE[1]+=t[1]-DE[1],IE[2]+=t[2]-DE[2],IE[3]+=t[0]-DE[0],IE[4]+=t[1]-DE[1],IE[5]+=t[2]-DE[2],r.viewer.cameraFlight.flyTo({aabb:IE,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=new hn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new EE(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}},{key:"destroySectionPlane",value:function(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"StoreyViews",e))._objectsMemento=new Ad,r._cameraMemento=new od,r.storeys={},r.modelStoreys={},r._fitStoreyMaps=!!s.fitStoreyMaps,r._onModelLoaded=r.viewer.scene.on("modelLoaded",(function(e){r._registerModelStoreys(e),r.fire("storeys",r.storeys)})),r}return C(i,[{key:"_registerModelStoreys",value:function(e){var t=this,i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaModels[e],o=r.models[e];if(n&&n.rootMetaObjects)for(var a=n.rootMetaObjects,l=0,u=a.length;l.5?p.length:0,g=new TE(this,o.aabb,f,e,d,v);g._onModelDestroyed=o.once("destroyed",(function(){t._deregisterModelStoreys(e),t.fire("storeys",t.storeys)})),this.storeys[d]=g,this.modelStoreys[e]||(this.modelStoreys[e]={}),this.modelStoreys[e][d]=g}}},{key:"_deregisterModelStoreys",value:function(e){var t=this.modelStoreys[e];if(t){var i=this.viewer.scene;for(var r in t)if(t.hasOwnProperty(r)){var s=t[r],n=i.models[s.modelId];n&&n.off(s._onModelDestroyed),delete this.storeys[r]}delete this.modelStoreys[e]}}},{key:"fitStoreyMaps",get:function(){return this._fitStoreyMaps}},{key:"gotoStoreyCamera",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),void(t.done&&t.done());var r=this.viewer,s=r.scene,n=s.camera,o=i.storeyAABB;if(o[3]1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(i){var r=this.viewer,s=r.scene,n=r.metaScene,o=n.metaObjects[e];o&&(t.hideOthers&&s.setObjectsVisible(r.scene.visibleObjectIds,!1),this.withStoreyObjects(e,(function(e,t){e&&(e.visible=!0)})))}else this.error("IfcBuildingStorey not found with this ID: "+e)}},{key:"withStoreyObjects",value:function(e,t){var i=this.viewer,r=i.scene,s=i.metaScene,n=s.metaObjects[e];if(n)for(var o=n.getObjectIDsInSubtree(),a=0,l=o.length;a1&&void 0!==arguments[1]?arguments[1]:{},i=this.storeys[e];if(!i)return this.error("IfcBuildingStorey not found with this ID: "+e),OE;var r,s,n=this.viewer,o=n.scene,a=t.format||"png",l=this._fitStoreyMaps?i.storeyAABB:i.modelAABB,u=Math.abs((l[5]-l[2])/(l[3]-l[0])),A=t.padding||0;t.width&&t.height?(r=t.width,s=t.height):t.height?(s=t.height,r=Math.round(s/u)):t.width?(r=t.width,s=Math.round(r*u)):(r=300,s=Math.round(r*u)),this._objectsMemento.saveObjects(o),this._cameraMemento.saveCamera(o),this.showStoreyObjects(e,le.apply(t,{hideOthers:!0})),this._arrangeStoreyMapCamera(i);var c=n.getSnapshot({width:r,height:s,format:a});return this._objectsMemento.restoreObjects(o),this._cameraMemento.restoreCamera(o),new LE(e,c,a,r,s,A)}},{key:"_arrangeStoreyMapCamera",value:function(e){var t=this.viewer,i=t.scene.camera,r=this._fitStoreyMaps?e.storeyAABB:e.modelAABB,s=$.getAABB3Center(r),n=RE;n[0]=s[0]+.5*i.worldUp[0],n[1]=s[1]+.5*i.worldUp[1],n[2]=s[2]+.5*i.worldUp[2];var o=i.worldForward;t.cameraFlight.jumpTo({eye:n,look:s,up:o});var a=(r[3]-r[0])/2,l=(r[4]-r[1])/2,u=(r[5]-r[2])/2,A=-a,c=+a,h=-l,d=+l,p=-u,f=+u;t.camera.customProjection.matrix=$.orthoMat4c(A,c,p,f,h,d,UE),t.camera.projection="customProjection"}},{key:"pickStoreyMap",value:function(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),null;var n=1-t[0]/e.width,o=1-t[1]/e.height,a=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,l=a[0],u=a[1],A=a[2],c=a[3],h=a[4],d=a[5],p=c-l,f=h-u,v=d-A,g=$.vec3([l+p*n,u+.5*f,A+v*o]),m=$.vec3([0,-1,0]),_=$.addVec3(g,m,RE),y=this.viewer.camera.worldForward,b=$.lookAtMat4v(g,_,y,UE),w=this.viewer.scene.pick({pickSurface:i.pickSurface,pickInvisible:!0,matrix:b});return w}},{key:"storeyMapToWorldPos",value:function(e,t){var i=e.storeyId,r=this.storeys[i];if(!r)return this.error("IfcBuildingStorey not found with this ID: "+i),null;var s=1-t[0]/e.width,n=1-t[1]/e.height,o=this._fitStoreyMaps?r.storeyAABB:r.modelAABB,a=o[0],l=o[1],u=o[2],A=o[3],c=o[4],h=o[5],d=A-a,p=c-l,f=h-u,v=$.vec3([a+d*s,l+.5*p,u+f*n]);return v}},{key:"getStoreyContainingWorldPos",value:function(e){for(var t in this.storeys){var i=this.storeys[t];if($.point3AABB3Intersect(i.storeyAABB,e))return t}return null}},{key:"worldPosToStoreyMap",value:function(e,t,i){var r=e.storeyId,s=this.storeys[r];if(!s)return this.error("IfcBuildingStorey not found with this ID: "+r),!1;var n=this._fitStoreyMaps?s.storeyAABB:s.modelAABB,o=n[0],a=n[1],l=n[2],u=n[3]-o,A=n[4]-a,c=n[5]-l,h=this.viewer.camera.worldUp,d=h[0]>h[1]&&h[0]>h[2],p=!d&&h[1]>h[0]&&h[1]>h[2];!d&&!p&&h[2]>h[0]&&(h[2],h[1]);var f=e.width/u,v=p?e.height/c:e.height/A;return i[0]=Math.floor(e.width-(t[0]-o)*f),i[1]=Math.floor(e.height-(t[2]-l)*v),i[0]>=0&&i[0]=0&&i[1]<=e.height}},{key:"worldDirToStoreyMap",value:function(e,t,i){var r=this.viewer.camera,s=r.eye,n=r.look,o=$.subVec3(n,s,RE),a=r.worldUp,l=a[0]>a[1]&&a[0]>a[2],u=!l&&a[1]>a[0]&&a[1]>a[2];!l&&!u&&a[2]>a[0]&&(a[2],a[1]),l?(i[0]=o[1],i[1]=o[2]):u?(i[0]=o[0],i[1]=o[2]):(i[0]=o[0],i[1]=o[1]),$.normalizeVec2(i)}},{key:"destroy",value:function(){this.viewer.scene.off(this._onModelLoaded),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),QE=new Float64Array([0,0,1]),VE=new Float64Array(4),HE=function(){function e(t){x(this,e),this.id=null,this._viewer=t.viewer,this._plugin=t,this._visible=!1,this._pos=$.vec3(),this._origin=$.vec3(),this._rtcPos=$.vec3(),this._baseDir=$.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}return C(e,[{key:"_setSectionPlane",value:function(e){var t=this;this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(function(){t._setPos(t._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(function(){t._ignoreNextSectionPlaneDirUpdate?t._ignoreNextSectionPlaneDirUpdate=!1:t._setDir(t._sectionPlane.dir)})))}},{key:"sectionPlane",get:function(){return this._sectionPlane}},{key:"_setPos",value:function(e){this._pos.set(e),Re(this._pos,this._origin,this._rtcPos),this._rootNode.origin=this._origin,this._rootNode.position=this._rtcPos}},{key:"_setDir",value:function(e){this._baseDir.set(e),this._rootNode.quaternion=$.vec3PairToQuaternion(QE,e,VE)}},{key:"_setSectionPlaneDir",value:function(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}},{key:"getVisible",value:function(){return this._visible}},{key:"setCulled",value:function(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}},{key:"_createNodes",value:function(){var e=!1,t=this._viewer.scene,i=.01;this._rootNode=new wn(t,{position:[0,0,0],scale:[5,5,5]});var r=this._rootNode,s={arrowHead:new Ti(r,an({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ti(r,an({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),axis:new Ti(r,an({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},n={red:new Ni(r,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),green:new Ni(r,{diffuse:[0,1,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),blue:new Ni(r,{diffuse:[0,0,1],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new Vi(r,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6})};this._displayMeshes={plane:r.addChild(new nn(r,{geometry:new Ti(r,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new Ni(r,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:r.addChild(new nn(r,{geometry:new Ti(r,Jn({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(r,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),center:r.addChild(new nn(r,{geometry:new Ti(r,ln({radius:.05})),material:n.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:r.addChild(new nn(r,{geometry:s.arrowHead,material:n.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zShaft:r.addChild(new nn(r,{geometry:s.axis,material:n.blue,matrix:function(){var e=$.translateMat4c(0,.5,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[1,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:r.addChild(new nn(r,{geometry:new Ti(r,Jn({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new Ni(r,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new Vi(r,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),e),zAxisArrow:r.addChild(new nn(r,{geometry:s.arrowHeadBig,material:n.blue,matrix:function(){var e=$.translateMat4c(0,1.1,0,$.identityMat4()),t=$.rotationMat4v(-90*$.DEGTORAD,[.8,0,0],$.identityMat4());return $.mulMat4(t,e,$.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}},{key:"_bindEvents",value:function(){var e=this,t=this._rootNode,i=$.vec2(),r=this._viewer.camera,s=this._viewer.scene,n=0,o=!1,a=$.vec3([0,0,0]),l=-1;this._onCameraViewMatrix=s.camera.on("viewMatrix",(function(){})),this._onCameraProjMatrix=s.camera.on("projMatrix",(function(){})),this._onSceneTick=s.on("tick",(function(){o=!1;var i=Math.abs($.lenVec3($.subVec3(s.camera.eye,e._pos,a)));if(i!==l&&"perspective"===r.projection){var u=.07*(Math.tan(r.perspective.fov*$.DEGTORAD)*i);t.scale=[u,u,u],l=i}if("ortho"===r.projection){var c=r.ortho.scale/10;t.scale=[c,c,c],l=i}0!==n&&(A(n),n=0)}));var u=function(){var e=new Float64Array(2);return function(t){if(t){for(var i=t.target,r=0,s=0;i.offsetParent;)r+=i.offsetLeft,s+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-r,e[1]=t.pageY-s}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),A=function(t){var i=e._sectionPlane.pos,r=e._sectionPlane.dir;$.addVec3(i,$.mulVec3Scalar(r,.1*t*e._plugin.getDragSensitivity(),$.vec3())),e._sectionPlane.pos=i},c=!1;this._plugin._controlElement.addEventListener("mousedown",this._canvasMouseDownListener=function(t){if(t.preventDefault(),e._visible&&(e._viewer.cameraControl.pointerEnabled=!1,1===t.which)){c=!0;var r=u(t);i[0]=r[0],i[1]=r[1]}}),this._plugin._controlElement.addEventListener("mousemove",this._canvasMouseMoveListener=function(t){if(e._visible&&c&&!o){var r=u(t),s=r[0],n=r[1];A(n-i[1]),i[0]=s,i[1]=n}}),this._plugin._controlElement.addEventListener("mouseup",this._canvasMouseUpListener=function(t){e._visible&&(e._viewer.cameraControl.pointerEnabled=!0,c&&(t.which,c=!1))}),this._plugin._controlElement.addEventListener("wheel",this._canvasWheelListener=function(t){e._visible&&(n+=Math.max(-1,Math.min(1,40*-t.deltaY)))});var h,d,p=null;this._plugin._controlElement.addEventListener("touchstart",this._handleTouchStart=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=t.touches[0].clientY,p=h,n=0)}),this._plugin._controlElement.addEventListener("touchmove",this._handleTouchMove=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(o||(o=!0,d=t.touches[0].clientY,null!==p&&(n+=d-p),p=d))}),this._plugin._controlElement.addEventListener("touchend",this._handleTouchEnd=function(t){t.stopPropagation(),t.preventDefault(),e._visible&&(h=null,d=null,n=0)})}},{key:"_destroy",value:function(){this._unbindEvents(),this._destroyNodes()}},{key:"_unbindEvents",value:function(){var e=this._viewer,t=e.scene,i=t.canvas.canvas,r=e.camera,s=this._plugin._controlElement;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.removeEventListener("touchstart",this._handleTouchStart),s.removeEventListener("touchmove",this._handleTouchMove),s.removeEventListener("touchend",this._handleTouchEnd),r.off(this._onCameraViewMatrix),r.off(this._onCameraProjMatrix)}},{key:"_destroyNodes",value:function(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}]),e}(),jE=function(){function e(t,i,r){var s=this;x(this,e),this.id=r.id,this._sectionPlane=r,this._mesh=new nn(i,{id:r.id,geometry:new Ti(i,Li({xSize:.5,ySize:.5,zSize:.001})),material:new Ni(i,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new ji(i,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new Vi(i,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new Vi(i,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});var n=$.vec3([0,0,0]),o=$.vec3(),a=$.vec3([0,0,1]),l=$.vec4(4),u=$.vec3(),A=function(){var e=s._sectionPlane.scene.center,t=[-s._sectionPlane.dir[0],-s._sectionPlane.dir[1],-s._sectionPlane.dir[2]];$.subVec3(e,s._sectionPlane.pos,n);var i=-$.dotVec3(t,n);$.normalizeVec3(t),$.mulVec3Scalar(t,i,o);var r=$.vec3PairToQuaternion(a,s._sectionPlane.dir,l);u[0]=.1*o[0],u[1]=.1*o[1],u[2]=.1*o[2],s._mesh.quaternion=r,s._mesh.position=u};this._onSectionPlanePos=this._sectionPlane.on("pos",A),this._onSectionPlaneDir=this._sectionPlane.on("dir",A),this._highlighted=!1,this._selected=!1}return C(e,[{key:"setHighlighted",value:function(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}},{key:"getHighlighted",value:function(){return this._highlighted}},{key:"setSelected",value:function(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}},{key:"getSelected",value:function(){return this._selected}},{key:"destroy",value:function(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}]),e}(),GE=function(){function e(t,i){var r=this;if(x(this,e),!(i.onHoverEnterPlane&&i.onHoverLeavePlane&&i.onClickedNothing&&i.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=t,this._viewer=t.viewer,this._onHoverEnterPlane=i.onHoverEnterPlane,this._onHoverLeavePlane=i.onHoverLeavePlane,this._onClickedNothing=i.onClickedNothing,this._onClickedPlane=i.onClickedPlane,this._visible=!0,this._planes={},this._canvas=i.overviewCanvas,this._scene=new $i(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new bi(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new bi(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new bi(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;var s=this._scene.camera,n=$.rotationMat4c(-90*$.DEGTORAD,1,0,0),o=$.vec3(),a=$.vec3(),l=$.vec3();this._synchCamera=function(){var e=r._viewer.camera.eye,t=r._viewer.camera.look,i=r._viewer.camera.up;$.mulVec3Scalar($.normalizeVec3($.subVec3(e,t,o)),7),r._zUp?($.transformVec3(n,o,a),$.transformVec3(n,i,l),s.look=[0,0,0],s.eye=$.transformVec3(n,o,a),s.up=$.transformPoint3(n,i,l)):(s.look=[0,0,0],s.eye=o,s.up=i)},this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",(function(e){r._scene.camera.perspective.fov=e}));var u=null;this._onInputMouseMove=this._scene.input.on("mousemove",(function(e){var t=r._scene.pick({canvasPos:e});if(t){if(!u||t.entity.id!==u.id){if(u)r._planes[u.id]&&r._onHoverLeavePlane(u.id);u=t.entity,r._planes[u.id]&&r._onHoverEnterPlane(u.id)}}else u&&(r._onHoverLeavePlane(u.id),u=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=function(){u?r._planes[u.id]&&r._onClickedPlane(u.id):r._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=function(){u&&(r._onHoverLeavePlane(u.id),u=null)}),this.setVisible(i.overviewVisible)}return C(e,[{key:"addSectionPlane",value:function(e){this._planes[e.id]=new jE(this,this._scene,e)}},{key:"setPlaneHighlighted",value:function(e,t){var i=this._planes[e];i&&i.setHighlighted(t)}},{key:"setPlaneSelected",value:function(e,t){var i=this._planes[e];i&&i.setSelected(t)}},{key:"removeSectionPlane",value:function(e){var t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}},{key:"setVisible",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}},{key:"getVisible",value:function(){return this._visible}},{key:"destroy",value:function(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}]),e}(),zE=$.AABB3(),WE=$.vec3(),KE=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,"FaceAlignedSectionPlanesPlugin",e))._freeControls=[],r._sectionPlanes=e.scene.sectionPlanes,r._controls={},r._shownControlId=null,r._dragSensitivity=s.dragSensitivity||1,null!==s.overviewCanvasId&&void 0!==s.overviewCanvasId){var n=document.getElementById(s.overviewCanvasId);n?r._overview=new GE(b(r),{overviewCanvas:n,visible:s.overviewVisible,onHoverEnterPlane:function(e){r._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:function(e){r._overview.setPlaneHighlighted(e,!1)},onClickedPlane:function(e){if(r.getShownControl()!==e){r.showControl(e);var t=r.sectionPlanes[e].pos;zE.set(r.viewer.scene.aabb),$.getAABB3Center(zE,WE),zE[0]+=t[0]-WE[0],zE[1]+=t[1]-WE[1],zE[2]+=t[2]-WE[2],zE[3]+=t[0]-WE[0],zE[4]+=t[1]-WE[1],zE[5]+=t[2]-WE[2],r.viewer.cameraFlight.flyTo({aabb:zE,fitFOV:65})}else r.hideControl()},onClickedNothing:function(){r.hideControl()}}):r.warn("Can't find overview canvas: '"+s.overviewCanvasId+"' - will create plugin without overview")}return null===s.controlElementId||void 0===s.controlElementId?r.error("Parameter expected: controlElementId"):(r._controlElement=document.getElementById(s.controlElementId),r._controlElement||r.warn("Can't find control element: '"+s.controlElementId+"' - will create plugin without control element")),r._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(function(e){r._sectionPlaneCreated(e)})),r}return C(i,[{key:"setDragSensitivity",value:function(e){this._dragSensitivity=e||1}},{key:"getDragSensitivity",value:function(){return this._dragSensitivity}},{key:"setOverviewVisible",value:function(e){this._overview&&this._overview.setVisible(e)}},{key:"getOverviewVisible",value:function(){if(this._overview)return this._overview.getVisible()}},{key:"sectionPlanes",get:function(){return this._sectionPlanes}},{key:"createSectionPlane",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id);var t=new hn(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0});return t}},{key:"_sectionPlaneCreated",value:function(e){var t=this,i=this._freeControls.length>0?this._freeControls.pop():new HE(this);i._setSectionPlane(e),i.setVisible(!1),this._controls[e.id]=i,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(function(){t._sectionPlaneDestroyed(e)}))}},{key:"flipSectionPlanes",value:function(){var e=this.viewer.scene.sectionPlanes;for(var t in e){e[t].flipDir()}}},{key:"showControl",value:function(e){var t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}},{key:"getShownControl",value:function(){return this._shownControlId}},{key:"hideControl",value:function(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}},{key:"destroySectionPlane",value:function(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}},{key:"_sectionPlaneDestroyed",value:function(e){this._overview&&this._overview.removeSectionPlane(e);var t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}},{key:"clear",value:function(){for(var e=Object.keys(this._sectionPlanes),t=0,i=e.length;t0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getSTL",value:function(e,t,i){e=this._cacheBusterURL(e);var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.responseType="arraybuffer",r.onreadystatechange=function(){4===r.readyState&&(200===r.status?t(r.response):i(r.statusText))},r.send(null)}}]),e}(),JE=$.vec3(),ZE=function(){function e(){x(this,e)}return C(e,[{key:"load",value:function(e,t,i,r,s,n){r=r||{};var o=e.viewer.scene.canvas.spinner;o.processes++,e.dataSource.getSTL(i,(function(i){!function(e,t,i,r){try{var s=rF(i);qE(s)?$E(e,s,t,r):eF(e,iF(i),t,r)}catch(e){t.fire("error",e)}}(e,t,i,r);try{var a=rF(i);qE(a)?$E(e,a,t,r):eF(e,iF(i),t,r),o.processes--,_e.scheduleTask((function(){t.fire("loaded",!0,!1)})),s&&s()}catch(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}}),(function(i){o.processes--,e.error(i),n&&n(i),t.fire("error",i)}))}},{key:"parse",value:function(e,t,i,r){var s=e.viewer.scene.canvas.spinner;s.processes++;try{var n=rF(i);qE(n)?$E(e,n,t,r):eF(e,iF(i),t,r),s.processes--,_e.scheduleTask((function(){t.fire("loaded",!0,!1)}))}catch(e){s.processes--,t.fire("error",e)}}}]),e}();function qE(e){var t=new DataView(e);if(84+50*t.getUint32(80,!0)===t.byteLength)return!0;for(var i=[115,111,108,105,100],r=0;r<5;r++)if(i[r]!==t.getUint8(r,!1))return!0;return!1}function $E(e,t,i,r){for(var s,n,o,a,l,u,A,c=new DataView(t),h=c.getUint32(80,!0),d=!1,p=null,f=null,v=null,g=!1,m=0;m<70;m++)1129270351===c.getUint32(m,!1)&&82===c.getUint8(m+4)&&61===c.getUint8(m+5)&&(d=!0,a=[],l=c.getUint8(m+6)/255,u=c.getUint8(m+7)/255,A=c.getUint8(m+8)/255,c.getUint8(m+9));for(var _=new Cn(i,{roughness:.5}),y=[],b=[],w=r.splitMeshes,B=0;B>5&31)/31,o=(E>>10&31)/31):(s=l,n=u,o=A),(w&&s!==p||n!==f||o!==v)&&(null!==p&&(g=!0),p=s,f=n,v=o)}for(var F=1;F<=3;F++){var k=x+12*F;y.push(c.getFloat32(k,!0)),y.push(c.getFloat32(k+4,!0)),y.push(c.getFloat32(k+8,!0)),b.push(P,C,M),d&&a.push(s,n,o,1)}w&&g&&(tF(i,y,b,a,_,r),y=[],b=[],a=a?[]:null,g=!1)}y.length>0&&tF(i,y,b,a,_,r)}function eF(e,t,i,r){for(var s,n,o,a,l,u,A,c=/facet([\s\S]*?)endfacet/g,h=0,d=/[\s]+([+-]?(?:\d+.\d+|\d+.|\d+|.\d+)(?:[eE][+-]?\d+)?)/.source,p=new RegExp("vertex"+d+d+d,"g"),f=new RegExp("normal"+d+d+d,"g"),v=[],g=[];null!==(a=c.exec(t));){for(l=0,u=0,A=a[0];null!==(a=f.exec(A));)s=parseFloat(a[1]),n=parseFloat(a[2]),o=parseFloat(a[3]),u++;for(;null!==(a=p.exec(A));)v.push(parseFloat(a[1]),parseFloat(a[2]),parseFloat(a[3])),g.push(s,n,o),l++;1!==u&&e.error("Error in normal of face "+h),3!==l&&e.error("Error in positions of face "+h),h++}tF(i,v,g,null,new Cn(i,{roughness:.5}),r)}function tF(e,t,i,r,s,n){for(var o=new Int32Array(t.length/3),a=0,l=o.length;a0?i:null,r=r&&r.length>0?r:null,n.smoothNormals&&$.faceToVertexNormals(t,i,n);var u=JE;Ue(t,t,u);var A=new Ti(e,{primitive:"triangles",positions:t,normals:i,colors:r,indices:o}),c=new nn(e,{origin:0!==u[0]||0!==u[1]||0!==u[2]?u:null,geometry:A,material:s,edges:n.edges});e.addChild(c)}function iF(e){return"string"!=typeof e?function(e){if("undefined"!=typeof TextDecoder)return(new TextDecoder).decode(e);for(var t="",i=0,r=e.length;i1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"STLLoader",e,s))._sceneGraphLoader=new ZE,r.dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new YE}},{key:"load",value:function(e){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new wn(this.viewer.scene,le.apply(e,{isModel:!0})),i=e.src,r=e.stl;return i||r?(i?this._sceneGraphLoader.load(this,t,i,e):this._sceneGraphLoader.parse(this,t,r,e),t):(this.error("load() param expected: either 'src' or 'stl'"),t)}}]),i}(),nF=function(){function e(){x(this,e)}return C(e,[{key:"createRootNode",value:function(){return document.createElement("ul")}},{key:"createNodeElement",value:function(e,t,i,r,s){var n=document.createElement("li");if(n.id=e.nodeId,e.xrayed&&n.classList.add("xrayed-node"),e.children.length>0){var o=document.createElement("a");o.href="#",o.id="switch-".concat(e.nodeId),o.textContent="+",o.classList.add("plus"),t&&o.addEventListener("click",t),n.appendChild(o)}var a=document.createElement("input");a.id="checkbox-".concat(e.nodeId),a.type="checkbox",a.checked=e.checked,a.style["pointer-events"]="all",i&&a.addEventListener("change",i),n.appendChild(a);var l=document.createElement("span");return l.textContent=e.title,n.appendChild(l),r&&(l.oncontextmenu=r),s&&(l.onclick=s),n}},{key:"createDisabledNodeElement",value:function(e){var t=document.createElement("li"),i=document.createElement("a");i.href="#",i.textContent="!",i.classList.add("warn"),i.classList.add("warning"),t.appendChild(i);var r=document.createElement("span");return r.textContent=e,t.appendChild(r),t}},{key:"addChildren",value:function(e,t){var i=document.createElement("ul");t.forEach((function(e){i.appendChild(e)})),e.parentElement.appendChild(i)}},{key:"expand",value:function(e,t,i){e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",t),e.addEventListener("click",i)}},{key:"collapse",value:function(e,t,i){if(e){var r=e.parentElement;if(r){var s=r.querySelector("ul");s&&(r.removeChild(s),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",i),e.addEventListener("click",t))}}}},{key:"isExpanded",value:function(e){return void 0!==e.parentElement.getElementsByTagName("li")[0]}},{key:"getId",value:function(e){return e.parentElement.id}},{key:"getIdFromCheckbox",value:function(e){return e.id.replace("checkbox-","")}},{key:"getSwitchElement",value:function(e){return document.getElementById("switch-".concat(e))}},{key:"isChecked",value:function(e){return e.checked}},{key:"setCheckbox",value:function(e,t){var i=document.getElementById("checkbox-".concat(e));i&&t!==i.checked&&(i.checked=t)}},{key:"setXRayed",value:function(e,t){var i=document.getElementById(e);i&&(t?i.classList.add("xrayed-node"):i.classList.remove("xrayed-node"))}},{key:"setHighlighted",value:function(e,t){var i=document.getElementById(e);i&&(t?(i.scrollIntoView({block:"center"}),i.classList.add("highlighted-node")):i.classList.remove("highlighted-node"))}}]),e}(),oF=[],aF=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,i),(r=t.call(this,"TreeViewPlugin",e)).errors=[],r.valid=!0;var n=s.containerElement||document.getElementById(s.containerElementId);if(!(n instanceof HTMLElement))return r.error("Mandatory config expected: valid containerElementId or containerElement"),y(r);for(var o=0;;o++)if(!oF[o]){oF[o]=b(r),r._index=o,r._id="tree-".concat(o);break}if(r._containerElement=n,r._metaModels={},r._autoAddModels=!1!==s.autoAddModels,r._autoExpandDepth=s.autoExpandDepth||0,r._sortNodes=!1!==s.sortNodes,r._viewer=e,r._rootElement=null,r._muteSceneEvents=!1,r._muteTreeEvents=!1,r._rootNodes=[],r._objectNodes={},r._nodeNodes={},r._rootNames={},r._sortNodes=s.sortNodes,r._pruneEmptyNodes=s.pruneEmptyNodes,r._showListItemElementId=null,r._renderService=s.renderService||new nF,!r._renderService)throw new Error("TreeViewPlugin: no render service set");if(r._containerElement.oncontextmenu=function(e){e.preventDefault()},r._onObjectVisibility=r._viewer.scene.on("objectVisibility",(function(e){if(!r._muteSceneEvents){var t=e.id,i=r._objectNodes[t];if(i){var s=e.visible;if(s!==i.checked){r._muteTreeEvents=!0,i.checked=s,s?i.numVisibleEntities++:i.numVisibleEntities--,r._renderService.setCheckbox(i.nodeId,s);for(var n=i.parent;n;)n.checked=s,s?n.numVisibleEntities++:n.numVisibleEntities--,r._renderService.setCheckbox(n.nodeId,n.numVisibleEntities>0),n=n.parent;r._muteTreeEvents=!1}}}})),r._onObjectXrayed=r._viewer.scene.on("objectXRayed",(function(e){if(!r._muteSceneEvents){var t=e.id,i=r._objectNodes[t];if(i){r._muteTreeEvents=!0;var s=e.xrayed;s!==i.xrayed&&(i.xrayed=s,r._renderService.setXRayed(i.nodeId,s),r._muteTreeEvents=!1)}}})),r._switchExpandHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;r._expandSwitchElement(t)},r._switchCollapseHandler=function(e){e.preventDefault(),e.stopPropagation();var t=e.target;r._collapseSwitchElement(t)},r._checkboxChangeHandler=function(e){if(!r._muteTreeEvents){r._muteSceneEvents=!0;var t=e.target,i=r._renderService.isChecked(t),s=r._renderService.getIdFromCheckbox(t),n=r._nodeNodes[s],o=r._viewer.scene.objects,a=0;r._withNodeTree(n,(function(e){var t=e.objectId,s=o[t],n=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,n&&i!==e.checked&&a++,e.checked=i,r._renderService.setCheckbox(e.nodeId,i),s&&(s.visible=i)}));for(var l=n.parent;l;)l.checked=i,i?l.numVisibleEntities+=a:l.numVisibleEntities-=a,r._renderService.setCheckbox(l.nodeId,l.numVisibleEntities>0),l=l.parent;r._muteSceneEvents=!1}},r._hierarchy=s.hierarchy||"containment",r._autoExpandDepth=s.autoExpandDepth||0,r._autoAddModels){for(var a=Object.keys(r.viewer.metaScene.metaModels),l=0,u=a.length;l1&&void 0!==arguments[1]?arguments[1]:{};if(this._containerElement){var r=this.viewer.scene.models[e];if(!r)throw"Model not found: "+e;var s=this.viewer.metaScene.metaModels[e];s?this._metaModels[e]?this.warn("Model already added: "+e):(this._metaModels[e]=s,i&&i.rootName&&(this._rootNames[e]=i.rootName),r.on("destroyed",(function(){t.removeModel(r.id)})),this._createNodes()):this.error("MetaModel not found: "+e)}}},{key:"removeModel",value:function(e){this._containerElement&&(this._metaModels[e]&&(this._rootNames[e]&&delete this._rootNames[e],delete this._metaModels[e],this._createNodes()))}},{key:"showNode",value:function(e){this.unShowNode();var t=this._objectNodes[e];if(t){var i=t.nodeId,r=this._renderService.getSwitchElement(i);if(r)return this._expandSwitchElement(r),r.scrollIntoView(),!0;var s=[];s.unshift(t);for(var n=t.parent;n;)s.unshift(n),n=n.parent;for(var o=0,a=s.length;o0;return this.valid}},{key:"_validateMetaModelForStoreysHierarchy",value:function(){return!0}},{key:"_createEnabledNodes",value:function(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this.error("Failed to build storeys hierarchy");break;case"types":this._createTypesNodes();break;default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}},{key:"_createDisabledNodes",value:function(){var e=this._renderService.createRootNode();this._rootElement=e,this._containerElement.appendChild(e);var t=this._viewer.metaScene.rootMetaObjects;for(var i in t){var r=t[i],s=r.type,n=r.name,o=n&&""!==n&&"Undefined"!==n&&"Default"!==n?n:s,a=this._renderService.createDisabledNodeElement(o);e.appendChild(a)}}},{key:"_findEmptyNodes",value:function(){var e=this._viewer.metaScene.rootMetaObjects;for(var t in e)this._findEmptyNodes2(e[t])}},{key:"_findEmptyNodes2",value:function(e){var t=this.viewer,i=t.scene,r=e.children,s=e.id,n=i.objects[s];if(e._countEntities=0,n&&e._countEntities++,r)for(var o=0,a=r.length;os.aabb[n]?-1:e.aabb[n]r?1:0}},{key:"_synchNodesToEntities",value:function(){for(var e=Object.keys(this.viewer.metaScene.metaObjects),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects,r=0,s=e.length;r0){for(var e=0;e1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"ViewCull",e))._objectCullStates=AF(e.scene),r._maxTreeDepth=s.maxTreeDepth||8,r._modelInfos={},r._frustum=new Me,r._kdRoot=null,r._frustumDirty=!1,r._kdTreeDirty=!1,r._onViewMatrix=e.scene.camera.on("viewMatrix",(function(){r._frustumDirty=!0})),r._onProjMatrix=e.scene.camera.on("projMatMatrix",(function(){r._frustumDirty=!0})),r._onModelLoaded=e.scene.on("modelLoaded",(function(e){var t=r.viewer.scene.models[e];t&&r._addModel(t)})),r._onSceneTick=e.scene.on("tick",(function(){r._doCull()})),r}return C(i,[{key:"enabled",get:function(){return this._enabled},set:function(e){this._enabled=e}},{key:"_addModel",value:function(e){var t=this,i={model:e,onDestroyed:e.on("destroyed",(function(){t._removeModel(e)}))};this._modelInfos[e.id]=i,this._kdTreeDirty=!0}},{key:"_removeModel",value:function(e){var t=this._modelInfos[e.id];t&&(t.model.off(t.onDestroyed),delete this._modelInfos[e.id],this._kdTreeDirty=!0)}},{key:"_doCull",value:function(){var e=this._frustumDirty||this._kdTreeDirty;if(this._frustumDirty&&this._buildFrustum(),this._kdTreeDirty&&this._buildKDTree(),e){var t=this._kdRoot;t&&this._visitKDNode(t)}}},{key:"_buildFrustum",value:function(){var e=this.viewer.scene.camera;Ee(this._frustum,e.viewMatrix,e.projMatrix),this._frustumDirty=!1}},{key:"_buildKDTree",value:function(){var e=this.viewer.scene;this._kdRoot,this._kdRoot={aabb:e.getAABB(),intersection:Me.INTERSECT};for(var t=0,i=this._objectCullStates.numObjects;t=this._maxTreeDepth)return e.objects=e.objects||[],e.objects.push(i),void $.expandAABB3(e.aabb,s);if(e.left&&$.containsAABB3(e.left.aabb,s))this._insertEntityIntoKDTree(e.left,t,i,r+1);else if(e.right&&$.containsAABB3(e.right.aabb,s))this._insertEntityIntoKDTree(e.right,t,i,r+1);else{var n=e.aabb;cF[0]=n[3]-n[0],cF[1]=n[4]-n[1],cF[2]=n[5]-n[2];var o=0;if(cF[1]>cF[o]&&(o=1),cF[2]>cF[o]&&(o=2),!e.left){var a=n.slice();if(a[o+3]=(n[o]+n[o+3])/2,e.left={aabb:a,intersection:Me.INTERSECT},$.containsAABB3(a,s))return void this._insertEntityIntoKDTree(e.left,t,i,r+1)}if(!e.right){var l=n.slice();if(l[o]=(n[o]+n[o+3])/2,e.right={aabb:l,intersection:Me.INTERSECT},$.containsAABB3(l,s))return void this._insertEntityIntoKDTree(e.right,t,i,r+1)}e.objects=e.objects||[],e.objects.push(i),$.expandAABB3(e.aabb,s)}}},{key:"_visitKDNode",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Me.INTERSECT;if(t===Me.INTERSECT||e.intersects!==t){t===Me.INTERSECT&&(t=Fe(this._frustum,e.aabb),e.intersects=t);var i=t===Me.OUTSIDE,r=e.objects;if(r&&r.length>0)for(var s=0,n=r.length;s0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getManifest",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getMetaModel",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}},{key:"getXKT",value:function(e,t,i){var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u=0;)e[t]=0}var i=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),r=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),s=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),n=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),o=new Array(576);t(o);var a=new Array(60);t(a);var l=new Array(512);t(l);var u=new Array(256);t(u);var A=new Array(29);t(A);var c,h,d,p=new Array(30);function f(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}function v(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}t(p);var g=function(e){return e<256?l[e]:l[256+(e>>>7)]},m=function(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},_=function(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1},w=function(e,t,i){var r,s,n=new Array(16),o=0;for(r=1;r<=15;r++)o=o+i[r-1]<<1,n[r]=o;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=b(n[a]++,a))}},x=function(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.sym_next=e.matches=0},P=function(e){e.bi_valid>8?m(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},C=function(e,t,i,r){var s=2*t,n=2*i;return e[s]>1;i>=1;i--)M(e,n,i);s=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],M(e,n,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,n[2*s]=n[2*i]+n[2*r],e.depth[s]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,n[2*i+1]=n[2*r+1]=s,e.heap[1]=s++,M(e,n,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,s,n,o,a,l=t.dyn_tree,u=t.max_code,A=t.stat_desc.static_tree,c=t.stat_desc.has_stree,h=t.stat_desc.extra_bits,d=t.stat_desc.extra_base,p=t.stat_desc.max_length,f=0;for(n=0;n<=15;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(n=l[2*l[2*(r=e.heap[i])+1]+1]+1)>p&&(n=p,f++),l[2*r+1]=n,r>u||(e.bl_count[n]++,o=0,r>=d&&(o=h[r-d]),a=l[2*r],e.opt_len+=a*(n+o),c&&(e.static_len+=a*(A[2*r+1]+o)));if(0!==f){do{for(n=p-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[p]--,f-=2}while(f>0);for(n=p;0!==n;n--)for(r=e.bl_count[n];0!==r;)(s=e.heap[--i])>u||(l[2*s+1]!==n&&(e.opt_len+=(n-l[2*s+1])*l[2*s],l[2*s+1]=n),r--)}}(e,t),w(n,u,e.bl_count)},k=function(e,t,i){var r,s,n=-1,o=t[1],a=0,l=7,u=4;for(0===o&&(l=138,u=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=o,o=t[2*(r+1)+1],++a>=7;v<30;v++)for(p[v]=g<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),F(e,e.l_desc),F(e,e.d_desc),u=function(e){var t;for(k(e,e.dyn_ltree,e.l_desc.max_code),k(e,e.dyn_dtree,e.d_desc.max_code),F(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*n[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(l=e.static_len+3+7>>>3)<=s&&(s=l)):s=l=i+5,i+4<=s&&-1!==t?S(e,t,i,r):4===e.strategy||l===s?(_(e,2+(r?1:0),3),E(e,o,a)):(_(e,4+(r?1:0),3),function(e,t,i,r){var s;for(_(e,t-257,5),_(e,i-1,5),_(e,r-4,4),s=0;s>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*g(t)]++),e.sym_next===e.sym_end},O=function(e){_(e,2,3),y(e,256,o),function(e){16===e.bi_valid?(m(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)},N=function(e,t,i,r){for(var s=65535&e|0,n=e>>>16&65535|0,o=0;0!==i;){i-=o=i>2e3?2e3:i;do{n=n+(s=s+t[r++]|0)|0}while(--o);s%=65521,n%=65521}return s|n<<16|0},Q=new Uint32Array(function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}()),V=function(e,t,i,r){var s=Q,n=r+i;e^=-1;for(var o=r;o>>8^s[255&(e^t[o])];return-1^e},H={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},j={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},G=T,z=L,W=R,K=U,X=O,Y=j.Z_NO_FLUSH,J=j.Z_PARTIAL_FLUSH,Z=j.Z_FULL_FLUSH,q=j.Z_FINISH,$=j.Z_BLOCK,ee=j.Z_OK,te=j.Z_STREAM_END,ie=j.Z_STREAM_ERROR,re=j.Z_DATA_ERROR,se=j.Z_BUF_ERROR,ne=j.Z_DEFAULT_COMPRESSION,oe=j.Z_FILTERED,ae=j.Z_HUFFMAN_ONLY,le=j.Z_RLE,ue=j.Z_FIXED,Ae=j.Z_UNKNOWN,ce=j.Z_DEFLATED,he=258,de=262,pe=42,fe=113,ve=666,ge=function(e,t){return e.msg=H[t],t},me=function(e){return 2*e-(e>4?9:0)},_e=function(e){for(var t=e.length;--t>=0;)e[t]=0},ye=function(e){var t,i,r,s=e.w_size;r=t=e.hash_size;do{i=e.head[--r],e.head[r]=i>=s?i-s:0}while(--t);r=t=s;do{i=e.prev[--r],e.prev[r]=i>=s?i-s:0}while(--t)},be=function(e,t,i){return(t<e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Be=function(e,t){W(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,we(e.strm)},xe=function(e,t){e.pending_buf[e.pending++]=t},Pe=function(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},Ce=function(e,t,i,r){var s=e.avail_in;return s>r&&(s=r),0===s?0:(e.avail_in-=s,t.set(e.input.subarray(e.next_in,e.next_in+s),i),1===e.state.wrap?e.adler=N(e.adler,t,s,i):2===e.state.wrap&&(e.adler=V(e.adler,t,s,i)),e.next_in+=s,e.total_in+=s,s)},Me=function(e,t){var i,r,s=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-de?e.strstart-(e.w_size-de):0,u=e.window,A=e.w_mask,c=e.prev,h=e.strstart+he,d=u[n+o-1],p=u[n+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(u[(i=t)+o]===p&&u[i+o-1]===d&&u[i]===u[n]&&u[++i]===u[n+1]){n+=2,i++;do{}while(u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&u[++n]===u[++i]&&no){if(e.match_start=t,o=r,r>=a)break;d=u[n+o-1],p=u[n+o]}}}while((t=c[t&A])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead},Ee=function(e){var t,i,r,s=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=s+(s-de)&&(e.window.set(e.window.subarray(s,s+s-i),0),e.match_start-=s,e.strstart-=s,e.block_start-=s,e.insert>e.strstart&&(e.insert=e.strstart),ye(e),i+=s),0===e.strm.avail_in)break;if(t=Ce(e.strm,e.window,e.strstart+e.lookahead,i),e.lookahead+=t,e.lookahead+e.insert>=3)for(r=e.strstart-e.insert,e.ins_h=e.window[r],e.ins_h=be(e,e.ins_h,e.window[r+1]);e.insert&&(e.ins_h=be(e,e.ins_h,e.window[r+3-1]),e.prev[r&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=r,r++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookaheade.w_size?e.w_size:e.pending_buf_size-5,o=0,a=e.strm.avail_in;do{if(i=65535,s=e.bi_valid+42>>3,e.strm.avail_out(r=e.strstart-e.block_start)+e.strm.avail_in&&(i=r+e.strm.avail_in),i>s&&(i=s),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,we(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(Ce(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===o);return(a-=e.strm.avail_in)&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waters&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(Ce(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water>3,n=(s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s)>e.w_size?e.w_size:s,((r=e.strstart-e.block_start)>=n||(r||t===q)&&t!==Y&&0===e.strm.avail_in&&r<=s)&&(i=r>s?s:r,o=t===q&&0===e.strm.avail_in&&i===r?1:0,z(e,e.block_start,i,o),e.block_start+=i,we(e.strm)),o?3:1)},ke=function(e,t){for(var i,r;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-de&&(e.match_length=Me(e,i)),e.match_length>=3)if(r=K(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=be(e,e.ins_h,e.window[e.strstart+1]);else r=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2},Ie=function(e,t){for(var i,r,s;;){if(e.lookahead=3&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=K(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=be(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(Be(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((r=K(e,0,e.window[e.strstart-1]))&&Be(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=K(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2};function De(e,t,i,r,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=s}var Se=[new De(0,0,0,0,Fe),new De(4,4,8,4,ke),new De(4,5,16,8,ke),new De(4,6,32,32,ke),new De(4,4,16,16,Ie),new De(8,16,32,32,Ie),new De(8,16,128,128,Ie),new De(8,32,128,256,Ie),new De(32,128,258,1024,Ie),new De(32,258,258,4096,Ie)];function Te(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ce,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),_e(this.dyn_ltree),_e(this.dyn_dtree),_e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),_e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),_e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}var Le=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.status!==pe&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==fe&&t.status!==ve?1:0},Re=function(e){if(Le(e))return ge(e,ie);e.total_in=e.total_out=0,e.data_type=Ae;var t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?pe:fe,e.adler=2===t.wrap?0:1,t.last_flush=-2,G(t),ee},Ue=function(e){var t,i=Re(e);return i===ee&&((t=e.state).window_size=2*t.w_size,_e(t.head),t.max_lazy_match=Se[t.level].max_lazy,t.good_match=Se[t.level].good_length,t.nice_match=Se[t.level].nice_length,t.max_chain_length=Se[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i},Oe=function(e,t,i,r,s,n){if(!e)return ie;var o=1;if(t===ne&&(t=6),r<0?(o=0,r=-r):r>15&&(o=2,r-=16),s<1||s>9||i!==ce||r<8||r>15||t<0||t>9||n<0||n>ue||8===r&&1!==o)return ge(e,ie);8===r&&(r=9);var a=new Te;return e.state=a,a.strm=e,a.status=pe,a.wrap=o,a.gzhead=null,a.w_bits=r,a.w_size=1<$||t<0)return e?ge(e,ie):ie;var i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===ve&&t!==q)return ge(e,0===e.avail_out?se:ie);var r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(we(e),0===e.avail_out)return i.last_flush=-1,ee}else if(0===e.avail_in&&me(t)<=me(r)&&t!==q)return ge(e,se);if(i.status===ve&&0!==e.avail_in)return ge(e,se);if(i.status===pe&&0===i.wrap&&(i.status=fe),i.status===pe){var s=ce+(i.w_bits-8<<4)<<8;if(s|=(i.strategy>=ae||i.level<2?0:i.level<6?1:6===i.level?2:3)<<6,0!==i.strstart&&(s|=32),Pe(i,s+=31-s%31),0!==i.strstart&&(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),e.adler=1,i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee}if(57===i.status)if(e.adler=0,xe(i,31),xe(i,139),xe(i,8),i.gzhead)xe(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),xe(i,255&i.gzhead.time),xe(i,i.gzhead.time>>8&255),xe(i,i.gzhead.time>>16&255),xe(i,i.gzhead.time>>24&255),xe(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),xe(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(xe(i,255&i.gzhead.extra.length),xe(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=V(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(xe(i,0),xe(i,0),xe(i,0),xe(i,0),xe(i,0),xe(i,9===i.level?2:i.strategy>=ae||i.level<2?4:0),xe(i,3),i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee;if(69===i.status){if(i.gzhead.extra){for(var n=i.pending,o=(65535&i.gzhead.extra.length)-i.gzindex;i.pending+o>i.pending_buf_size;){var a=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+a),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex+=a,we(e),0!==i.pending)return i.last_flush=-1,ee;n=0,o-=a}var l=new Uint8Array(i.gzhead.extra);i.pending_buf.set(l.subarray(i.gzindex,i.gzindex+o),i.pending),i.pending+=o,i.gzhead.hcrc&&i.pending>n&&(e.adler=V(e.adler,i.pending_buf,i.pending-n,n)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){var u,A=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>A&&(e.adler=V(e.adler,i.pending_buf,i.pending-A,A)),we(e),0!==i.pending)return i.last_flush=-1,ee;A=0}u=i.gzindexA&&(e.adler=V(e.adler,i.pending_buf,i.pending-A,A)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){var c,h=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>h&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h)),we(e),0!==i.pending)return i.last_flush=-1,ee;h=0}c=i.gzindexh&&(e.adler=V(e.adler,i.pending_buf,i.pending-h,h))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(we(e),0!==i.pending))return i.last_flush=-1,ee;xe(i,255&e.adler),xe(i,e.adler>>8&255),e.adler=0}if(i.status=fe,we(e),0!==i.pending)return i.last_flush=-1,ee}if(0!==e.avail_in||0!==i.lookahead||t!==Y&&i.status!==ve){var d=0===i.level?Fe(i,t):i.strategy===ae?function(e,t){for(var i;;){if(0===e.lookahead&&(Ee(e),0===e.lookahead)){if(t===Y)return 1;break}if(e.match_length=0,i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2}(i,t):i.strategy===le?function(e,t){for(var i,r,s,n,o=e.window;;){if(e.lookahead<=he){if(Ee(e),e.lookahead<=he&&t===Y)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&((r=o[s=e.strstart-1])===o[++s]&&r===o[++s]&&r===o[++s])){n=e.strstart+he;do{}while(r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&r===o[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=K(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=K(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Be(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===q?(Be(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Be(e,!1),0===e.strm.avail_out)?1:2}(i,t):Se[i.level].func(i,t);if(3!==d&&4!==d||(i.status=ve),1===d||3===d)return 0===e.avail_out&&(i.last_flush=-1),ee;if(2===d&&(t===J?X(i):t!==$&&(z(i,0,0,!1),t===Z&&(_e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),we(e),0===e.avail_out))return i.last_flush=-1,ee}return t!==q?ee:i.wrap<=0?te:(2===i.wrap?(xe(i,255&e.adler),xe(i,e.adler>>8&255),xe(i,e.adler>>16&255),xe(i,e.adler>>24&255),xe(i,255&e.total_in),xe(i,e.total_in>>8&255),xe(i,e.total_in>>16&255),xe(i,e.total_in>>24&255)):(Pe(i,e.adler>>>16),Pe(i,65535&e.adler)),we(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?ee:te)},He=function(e){if(Le(e))return ie;var t=e.state.status;return e.state=null,t===fe?ge(e,re):ee},je=function(e,t){var i=t.length;if(Le(e))return ie;var r=e.state,s=r.wrap;if(2===s||1===s&&r.status!==pe||r.lookahead)return ie;if(1===s&&(e.adler=N(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===s&&(_e(r.head),r.strstart=0,r.block_start=0,r.insert=0);var n=new Uint8Array(r.w_size);n.set(t.subarray(i-r.w_size,i),0),t=n,i=r.w_size}var o=e.avail_in,a=e.next_in,l=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,Ee(r);r.lookahead>=3;){var u=r.strstart,A=r.lookahead-2;do{r.ins_h=be(r,r.ins_h,r.window[u+3-1]),r.prev[u&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=u,u++}while(--A);r.strstart=u,r.lookahead=2,Ee(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=a,e.input=l,e.avail_in=o,r.wrap=s,ee},Ge=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},ze=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=B(i))throw new TypeError(i+"must be non-object");for(var r in i)Ge(i,r)&&(e[r]=i[r])}}return e},We=function(e){for(var t=0,i=0,r=e.length;i=252?6:Ye>=248?5:Ye>=240?4:Ye>=224?3:Ye>=192?2:1;Xe[254]=Xe[254]=1;var Je=function(e){if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);var t,i,r,s,n,o=e.length,a=0;for(s=0;s>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},Ze=function(e,t){var i,r,s=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));var n=new Array(2*s);for(r=0,i=0;i4)n[r++]=65533,i+=a-1;else{for(o&=2===a?31:3===a?15:7;a>1&&i1?n[r++]=65533:o<65536?n[r++]=o:(o-=65536,n[r++]=55296|o>>10&1023,n[r++]=56320|1023&o)}}}return function(e,t){if(t<65534&&e.subarray&&Ke)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));for(var i="",r=0;re.length&&(t=e.length);for(var i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+Xe[e[i]]>t?i:t},$e=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},et=Object.prototype.toString,tt=j.Z_NO_FLUSH,it=j.Z_SYNC_FLUSH,rt=j.Z_FULL_FLUSH,st=j.Z_FINISH,nt=j.Z_OK,ot=j.Z_STREAM_END,at=j.Z_DEFAULT_COMPRESSION,lt=j.Z_DEFAULT_STRATEGY,ut=j.Z_DEFLATED;function At(e){this.options=ze({level:at,method:ut,chunkSize:16384,windowBits:15,memLevel:8,strategy:lt},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $e,this.strm.avail_out=0;var i=Ne(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==nt)throw new Error(H[i]);if(t.header&&Qe(this.strm,t.header),t.dictionary){var r;if(r="string"==typeof t.dictionary?Je(t.dictionary):"[object ArrayBuffer]"===et.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=je(this.strm,r))!==nt)throw new Error(H[i]);this._dict_set=!0}}function ct(e,t){var i=new At(t);if(i.push(e,!0),i.err)throw i.msg||H[i.err];return i.result}At.prototype.push=function(e,t){var i,r,s=this.strm,n=this.options.chunkSize;if(this.ended)return!1;for(r=t===~~t?t:!0===t?st:tt,"string"==typeof e?s.input=Je(e):"[object ArrayBuffer]"===et.call(e)?s.input=new Uint8Array(e):s.input=e,s.next_in=0,s.avail_in=s.input.length;;)if(0===s.avail_out&&(s.output=new Uint8Array(n),s.next_out=0,s.avail_out=n),(r===it||r===rt)&&s.avail_out<=6)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else{if((i=Ve(s,r))===ot)return s.next_out>0&&this.onData(s.output.subarray(0,s.next_out)),i=He(this.strm),this.onEnd(i),this.ended=!0,i===nt;if(0!==s.avail_out){if(r>0&&s.next_out>0)this.onData(s.output.subarray(0,s.next_out)),s.avail_out=0;else if(0===s.avail_in)break}else this.onData(s.output)}return!0},At.prototype.onData=function(e){this.chunks.push(e)},At.prototype.onEnd=function(e){e===nt&&(this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var ht=At,dt=ct,pt=function(e,t){return(t=t||{}).raw=!0,ct(e,t)},ft=function(e,t){return(t=t||{}).gzip=!0,ct(e,t)},vt=16209,gt=function(e,t){var i,r,s,n,o,a,l,u,A,c,h,d,p,f,v,g,m,_,y,b,w,B,x,P,C=e.state;i=e.next_in,x=e.input,r=i+(e.avail_in-5),s=e.next_out,P=e.output,n=s-(t-e.avail_out),o=s+(e.avail_out-257),a=C.dmax,l=C.wsize,u=C.whave,A=C.wnext,c=C.window,h=C.hold,d=C.bits,p=C.lencode,f=C.distcode,v=(1<>>=_=m>>>24,d-=_,0===(_=m>>>16&255))P[s++]=65535&m;else{if(!(16&_)){if(0==(64&_)){m=p[(65535&m)+(h&(1<<_)-1)];continue t}if(32&_){C.mode=16191;break e}e.msg="invalid literal/length code",C.mode=vt;break e}y=65535&m,(_&=15)&&(d<_&&(h+=x[i++]<>>=_,d-=_),d<15&&(h+=x[i++]<>>=_=m>>>24,d-=_,!(16&(_=m>>>16&255))){if(0==(64&_)){m=f[(65535&m)+(h&(1<<_)-1)];continue i}e.msg="invalid distance code",C.mode=vt;break e}if(b=65535&m,d<(_&=15)&&(h+=x[i++]<a){e.msg="invalid distance too far back",C.mode=vt;break e}if(h>>>=_,d-=_,b>(_=s-n)){if((_=b-_)>u&&C.sane){e.msg="invalid distance too far back",C.mode=vt;break e}if(w=0,B=c,0===A){if(w+=l-_,_2;)P[s++]=B[w++],P[s++]=B[w++],P[s++]=B[w++],y-=3;y&&(P[s++]=B[w++],y>1&&(P[s++]=B[w++]))}else{w=s-b;do{P[s++]=P[w++],P[s++]=P[w++],P[s++]=P[w++],y-=3}while(y>2);y&&(P[s++]=P[w++],y>1&&(P[s++]=P[w++]))}break}}break}}while(i>3,h&=(1<<(d-=y<<3))-1,e.next_in=i,e.next_out=s,e.avail_in=i=1&&0===F[b];b--);if(w>b&&(w=b),0===b)return s[n++]=20971520,s[n++]=20971520,a.bits=1,0;for(y=1;y0&&(0===e||1!==b))return-1;for(k[1]=0,m=1;m<15;m++)k[m+1]=k[m]+F[m];for(_=0;_852||2===e&&C>592)return 1;for(;;){p=m-x,o[_]+1=d?(f=I[o[_]-d],v=E[o[_]-d]):(f=96,v=0),l=1<>x)+(u-=l)]=p<<24|f<<16|v|0}while(0!==u);for(l=1<>=1;if(0!==l?(M&=l-1,M+=l):M=0,_++,0==--F[m]){if(m===b)break;m=t[i+o[_]]}if(m>w&&(M&c)!==A){for(0===x&&(x=w),h+=y,P=1<<(B=m-x);B+x852||2===e&&C>592)return 1;s[A=M&c]=w<<24|B<<16|h-n|0}}return 0!==M&&(s[h+M]=m-x<<24|64<<16|0),a.bits=w,0},Bt=j.Z_FINISH,xt=j.Z_BLOCK,Pt=j.Z_TREES,Ct=j.Z_OK,Mt=j.Z_STREAM_END,Et=j.Z_NEED_DICT,Ft=j.Z_STREAM_ERROR,kt=j.Z_DATA_ERROR,It=j.Z_MEM_ERROR,Dt=j.Z_BUF_ERROR,St=j.Z_DEFLATED,Tt=16180,Lt=16190,Rt=16191,Ut=16192,Ot=16194,Nt=16199,Qt=16200,Vt=16206,Ht=16209,jt=function(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)};function Gt(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var zt,Wt,Kt=function(e){if(!e)return 1;var t=e.state;return!t||t.strm!==e||t.mode16211?1:0},Xt=function(e){if(Kt(e))return Ft;var t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=Tt,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ct},Yt=function(e){if(Kt(e))return Ft;var t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Xt(e)},Jt=function(e,t){var i;if(Kt(e))return Ft;var r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?Ft:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,Yt(e))},Zt=function(e,t){if(!e)return Ft;var i=new Gt;e.state=i,i.strm=e,i.window=null,i.mode=Tt;var r=Jt(e,t);return r!==Ct&&(e.state=null),r},qt=!0,$t=function(e){if(qt){zt=new Int32Array(512),Wt=new Int32Array(32);for(var t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(wt(1,e.lens,0,288,zt,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;wt(2,e.lens,0,32,Wt,0,e.work,{bits:5}),qt=!1}e.lencode=zt,e.lenbits=9,e.distcode=Wt,e.distbits=5},ei=function(e,t,i,r){var s,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(n.window.set(t.subarray(i-n.wsize,i),0),n.wnext=0,n.whave=n.wsize):((s=n.wsize-n.wnext)>r&&(s=r),n.window.set(t.subarray(i-r,i-r+s),n.wnext),(r-=s)?(n.window.set(t.subarray(i-r,i),0),n.wnext=r,n.whave=n.wsize):(n.wnext+=s,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=V(i.check,M,2,0),u=0,A=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&u)<<8)+(u>>8))%31){e.msg="incorrect header check",i.mode=Ht;break}if((15&u)!==St){e.msg="unknown compression method",i.mode=Ht;break}if(A-=4,w=8+(15&(u>>>=4)),0===i.wbits&&(i.wbits=w),w>15||w>i.wbits){e.msg="invalid window size",i.mode=Ht;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0,i.mode=16182;case 16182:for(;A<32;){if(0===a)break e;a--,u+=r[n++]<>>8&255,M[2]=u>>>16&255,M[3]=u>>>24&255,i.check=V(i.check,M,4,0)),u=0,A=0,i.mode=16183;case 16183:for(;A<16;){if(0===a)break e;a--,u+=r[n++]<>8),512&i.flags&&4&i.wrap&&(M[0]=255&u,M[1]=u>>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0,i.mode=16184;case 16184:if(1024&i.flags){for(;A<16;){if(0===a)break e;a--,u+=r[n++]<>>8&255,i.check=V(i.check,M,2,0)),u=0,A=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&((d=i.length)>a&&(d=a),d&&(i.head&&(w=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(n,n+d),w)),512&i.flags&&4&i.wrap&&(i.check=V(i.check,r,d,n)),a-=d,n+=d,i.length-=d),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;d=0;do{w=r[n+d++],i.head&&w&&i.length<65536&&(i.head.name+=String.fromCharCode(w))}while(w&&d>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Rt;break;case 16189:for(;A<32;){if(0===a)break e;a--,u+=r[n++]<>>=7&A,A-=7&A,i.mode=Vt;break}for(;A<3;){if(0===a)break e;a--,u+=r[n++]<>>=1)){case 0:i.mode=16193;break;case 1:if($t(i),i.mode=Nt,t===Pt){u>>>=2,A-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=Ht}u>>>=2,A-=2;break;case 16193:for(u>>>=7&A,A-=7&A;A<32;){if(0===a)break e;a--,u+=r[n++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Ht;break}if(i.length=65535&u,u=0,A=0,i.mode=Ot,t===Pt)break e;case Ot:i.mode=16195;case 16195:if(d=i.length){if(d>a&&(d=a),d>l&&(d=l),0===d)break e;s.set(r.subarray(n,n+d),o),a-=d,n+=d,l-=d,o+=d,i.length-=d;break}i.mode=Rt;break;case 16196:for(;A<14;){if(0===a)break e;a--,u+=r[n++]<>>=5,A-=5,i.ndist=1+(31&u),u>>>=5,A-=5,i.ncode=4+(15&u),u>>>=4,A-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Ht;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,A-=3}for(;i.have<19;)i.lens[E[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,x={bits:i.lenbits},B=wt(0,i.lens,0,19,i.lencode,0,i.work,x),i.lenbits=x.bits,B){e.msg="invalid code lengths set",i.mode=Ht;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=r[n++]<>>=v,A-=v,i.lens[i.have++]=m;else{if(16===m){for(P=v+2;A>>=v,A-=v,0===i.have){e.msg="invalid bit length repeat",i.mode=Ht;break}w=i.lens[i.have-1],d=3+(3&u),u>>>=2,A-=2}else if(17===m){for(P=v+3;A>>=v)),u>>>=3,A-=3}else{for(P=v+7;A>>=v)),u>>>=7,A-=7}if(i.have+d>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Ht;break}for(;d--;)i.lens[i.have++]=w}}if(i.mode===Ht)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Ht;break}if(i.lenbits=9,x={bits:i.lenbits},B=wt(1,i.lens,0,i.nlen,i.lencode,0,i.work,x),i.lenbits=x.bits,B){e.msg="invalid literal/lengths set",i.mode=Ht;break}if(i.distbits=6,i.distcode=i.distdyn,x={bits:i.distbits},B=wt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,x),i.distbits=x.bits,B){e.msg="invalid distances set",i.mode=Ht;break}if(i.mode=Nt,t===Pt)break e;case Nt:i.mode=Qt;case Qt:if(a>=6&&l>=258){e.next_out=o,e.avail_out=l,e.next_in=n,e.avail_in=a,i.hold=u,i.bits=A,gt(e,h),o=e.next_out,s=e.output,l=e.avail_out,n=e.next_in,r=e.input,a=e.avail_in,u=i.hold,A=i.bits,i.mode===Rt&&(i.back=-1);break}for(i.back=0;g=(C=i.lencode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=A);){if(0===a)break e;a--,u+=r[n++]<>>=_,A-=_,i.back+=_}if(u>>>=v,A-=v,i.back+=v,i.length=m,0===g){i.mode=16205;break}if(32&g){i.back=-1,i.mode=Rt;break}if(64&g){e.msg="invalid literal/length code",i.mode=Ht;break}i.extra=15&g,i.mode=16201;case 16201:if(i.extra){for(P=i.extra;A>>=i.extra,A-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;g=(C=i.distcode[u&(1<>>16&255,m=65535&C,!((v=C>>>24)<=A);){if(0===a)break e;a--,u+=r[n++]<>_)])>>>16&255,m=65535&C,!(_+(v=C>>>24)<=A);){if(0===a)break e;a--,u+=r[n++]<>>=_,A-=_,i.back+=_}if(u>>>=v,A-=v,i.back+=v,64&g){e.msg="invalid distance code",i.mode=Ht;break}i.offset=m,i.extra=15&g,i.mode=16203;case 16203:if(i.extra){for(P=i.extra;A>>=i.extra,A-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Ht;break}i.mode=16204;case 16204:if(0===l)break e;if(d=h-l,i.offset>d){if((d=i.offset-d)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Ht;break}d>i.wnext?(d-=i.wnext,p=i.wsize-d):p=i.wnext-d,d>i.length&&(d=i.length),f=i.window}else f=s,p=o-i.offset,d=i.length;d>l&&(d=l),l-=d,i.length-=d;do{s[o++]=f[p++]}while(--d);0===i.length&&(i.mode=Qt);break;case 16205:if(0===l)break e;s[o++]=i.length,l--,i.mode=Qt;break;case Vt:if(i.wrap){for(;A<32;){if(0===a)break e;a--,u|=r[n++]<=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new $e,this.strm.avail_out=0;var i=ii(this.strm,t.windowBits);if(i!==ci)throw new Error(H[i]);if(this.header=new ai,ni(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=Je(t.dictionary):"[object ArrayBuffer]"===li.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=oi(this.strm,t.dictionary))!==ci))throw new Error(H[i])}function mi(e,t){var i=new gi(t);if(i.push(e),i.err)throw i.msg||H[i.err];return i.result}gi.prototype.push=function(e,t){var i,r,s,n=this.strm,o=this.options.chunkSize,a=this.options.dictionary;if(this.ended)return!1;for(r=t===~~t?t:!0===t?Ai:ui,"[object ArrayBuffer]"===li.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;;){for(0===n.avail_out&&(n.output=new Uint8Array(o),n.next_out=0,n.avail_out=o),(i=ri(n,r))===di&&a&&((i=oi(n,a))===ci?i=ri(n,r):i===fi&&(i=di));n.avail_in>0&&i===hi&&n.state.wrap>0&&0!==e[n.next_in];)ti(n),i=ri(n,r);switch(i){case pi:case fi:case di:case vi:return this.onEnd(i),this.ended=!0,!1}if(s=n.avail_out,n.next_out&&(0===n.avail_out||i===hi))if("string"===this.options.to){var l=qe(n.output,n.next_out),u=n.next_out-l,A=Ze(n.output,l);n.next_out=u,n.avail_out=o-u,u&&n.output.set(n.output.subarray(l,l+u),0),this.onData(A)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out));if(i!==ci||0!==s){if(i===hi)return i=si(this.strm),this.onEnd(i),this.ended=!0,!0;if(0===n.avail_in)break}}return!0},gi.prototype.onData=function(e){this.chunks.push(e)},gi.prototype.onEnd=function(e){e===ci&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=We(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var _i=function(e,t){return(t=t||{}).raw=!0,mi(e,t)},yi=ht,bi=dt,wi=pt,Bi=ft,xi=gi,Pi=mi,Ci=_i,Mi=mi,Ei=j,Fi={Deflate:yi,deflate:bi,deflateRaw:wi,gzip:Bi,Inflate:xi,inflate:Pi,inflateRaw:Ci,ungzip:Mi,constants:Ei};e.Deflate=yi,e.Inflate=xi,e.constants=Ei,e.default=Fi,e.deflate=bi,e.deflateRaw=wi,e.gzip=Bi,e.inflate=Pi,e.inflateRaw=Ci,e.ungzip=Mi,Object.defineProperty(e,"__esModule",{value:!0})}));var pF=Object.freeze({__proto__:null}),fF=window.pako||pF;fF.inflate||(fF=fF.default);var vF,gF=(vF=new Float32Array(3),function(e){return vF[0]=e[0]/255,vF[1]=e[1]/255,vF[2]=e[2]/255,vF});var mF={version:1,parse:function(e,t,i,r,s,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}(i),a=function(e){return{positions:new Uint16Array(fF.inflate(e.positions).buffer),normals:new Int8Array(fF.inflate(e.normals).buffer),indices:new Uint32Array(fF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(fF.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(fF.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(fF.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(fF.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(fF.inflate(e.meshColors).buffer),entityIDs:fF.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(fF.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(fF.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(fF.inflate(e.positionsDecodeMatrix).buffer)}}(o);!function(e,t,i,r,s,n){n.getNextId(),r.positionsCompression="precompressed",r.normalsCompression="precompressed";for(var o=i.positions,a=i.normals,l=i.indices,u=i.edgeIndices,A=i.meshPositions,c=i.meshIndices,h=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),f=i.entityMeshes,v=i.entityIsObjects,g=A.length,m=f.length,_=0;_v[t]?1:0}));for(var E=0;E1||(F[R]=k)}for(var U=0;U1,V=CF(g.subarray(4*O,4*O+3)),H=g[4*O+3]/255,j=a.subarray(d[O],N?a.length:d[O+1]),G=l.subarray(d[O],N?l.length:d[O+1]),z=u.subarray(p[O],N?u.length:p[O+1]),W=A.subarray(f[O],N?A.length:f[O+1]),K=c.subarray(v[O],v[O]+16);if(Q){var X="".concat(o,"-geometry.").concat(O);r.createGeometry({id:X,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K})}else{var Y="".concat(o,"-").concat(O);_[F[O]],r.createMesh(le.apply({},{id:Y,primitive:"triangles",positionsCompressed:j,normalsCompressed:G,indices:z,edgeIndices:W,positionsDecodeMatrix:K,color:V,opacity:H}))}}for(var J=0,Z=0;Z1){var oe="".concat(o,"-instance.").concat(J++),ae="".concat(o,"-geometry.").concat(ne),ue=16*b[Z],Ae=h.subarray(ue,ue+16);r.createMesh(le.apply({},{id:oe,geometryId:ae,matrix:Ae})),re.push(oe)}else re.push(ne)}re.length>0&&r.createEntity(le.apply({},{id:ee,isObject:!0,meshIds:re}))}}(0,0,a,r,0,n)}},EF=window.pako||pF;EF.inflate||(EF=EF.default);var FF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var kF={version:5,parse:function(e,t,i,r,s,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}(i),a=function(e){return{positions:new Float32Array(EF.inflate(e.positions).buffer),normals:new Int8Array(EF.inflate(e.normals).buffer),indices:new Uint32Array(EF.inflate(e.indices).buffer),edgeIndices:new Uint32Array(EF.inflate(e.edgeIndices).buffer),matrices:new Float32Array(EF.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(EF.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(EF.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(EF.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(EF.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(EF.inflate(e.primitiveInstances).buffer),eachEntityId:EF.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(EF.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(EF.inflate(e.eachEntityMatricesPortion).buffer)}}(o);!function(e,t,i,r,s,n){var o=n.getNextId();r.positionsCompression="disabled",r.normalsCompression="precompressed";for(var a=i.positions,l=i.normals,u=i.indices,A=i.edgeIndices,c=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,f=i.eachPrimitiveColor,v=i.primitiveInstances,g=JSON.parse(i.eachEntityId),m=i.eachEntityPrimitiveInstancesPortion,_=i.eachEntityMatricesPortion,y=h.length,b=v.length,w=new Uint8Array(y),B=g.length,x=0;x1||(P[D]=C)}for(var S=0;S1,R=FF(f.subarray(4*S,4*S+3)),U=f[4*S+3]/255,O=a.subarray(h[S],T?a.length:h[S+1]),N=l.subarray(h[S],T?l.length:h[S+1]),Q=u.subarray(d[S],T?u.length:d[S+1]),V=A.subarray(p[S],T?A.length:p[S+1]);if(L){var H="".concat(o,"-geometry.").concat(S);r.createGeometry({id:H,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V})}else{var j=S;g[P[S]],r.createMesh(le.apply({},{id:j,primitive:"triangles",positionsCompressed:O,normalsCompressed:N,indices:Q,edgeIndices:V,color:R,opacity:U}))}}for(var G=0,z=0;z1){var ee="instance."+G++,te="geometry"+$,ie=16*_[z],re=c.subarray(ie,ie+16);r.createMesh(le.apply({},{id:ee,geometryId:te,matrix:re})),Z.push(ee)}else Z.push($)}Z.length>0&&r.createEntity(le.apply({},{id:X,isObject:!0,meshIds:Z}))}}(0,0,a,r,0,n)}},IF=window.pako||pF;IF.inflate||(IF=IF.default);var DF,SF=(DF=new Float32Array(3),function(e){return DF[0]=e[0]/255,DF[1]=e[1]/255,DF[2]=e[2]/255,DF});var TF={version:6,parse:function(e,t,i,r,s,n){var o=function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:IF.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:IF.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){for(var o=n.getNextId(),a=i.positions,l=i.normals,u=i.indices,A=i.edgeIndices,c=i.matrices,h=i.reusedPrimitivesDecodeMatrix,d=i.eachPrimitivePositionsAndNormalsPortion,p=i.eachPrimitiveIndicesPortion,f=i.eachPrimitiveEdgeIndicesPortion,v=i.eachPrimitiveColorAndOpacity,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),_=i.eachEntityPrimitiveInstancesPortion,y=i.eachEntityMatricesPortion,b=i.eachTileAABB,w=i.eachTileEntitiesPortion,B=d.length,x=g.length,P=m.length,C=w.length,M=new Uint32Array(B),E=0;E1,re=te===B-1,se=a.subarray(d[te],re?a.length:d[te+1]),ne=l.subarray(d[te],re?l.length:d[te+1]),oe=u.subarray(p[te],re?u.length:p[te+1]),ae=A.subarray(f[te],re?A.length:f[te+1]),ue=SF(v.subarray(4*te,4*te+3)),Ae=v[4*te+3]/255,ce=n.getNextId();if(ie){var he="".concat(o,"-geometry.").concat(D,".").concat(te);N[he]||(r.createGeometry({id:he,primitive:"triangles",positionsCompressed:se,indices:oe,edgeIndices:ae,positionsDecodeMatrix:h}),N[he]=!0),r.createMesh(le.apply(Z,{id:ce,geometryId:he,origin:k,matrix:G,color:ue,opacity:Ae})),X.push(ce)}else r.createMesh(le.apply(Z,{id:ce,origin:k,primitive:"triangles",positionsCompressed:se,normalsCompressed:ne,indices:oe,edgeIndices:ae,positionsDecodeMatrix:O,color:ue,opacity:Ae})),X.push(ce)}X.length>0&&r.createEntity(le.apply(J,{id:H,isObject:!0,meshIds:X}))}}}(e,t,a,r,0,n)}},LF=window.pako||pF;LF.inflate||(LF=LF.default);var RF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function UF(e){for(var t=[],i=0,r=e.length;i1,ne=re===M-1,oe=RF(w.subarray(6*ie,6*ie+3)),ae=w[6*ie+3]/255,ue=w[6*ie+4]/255,Ae=w[6*ie+5]/255,ce=n.getNextId();if(se){var he=b[ie],de=h.slice(he,he+16),pe="".concat(o,"-geometry.").concat(R,".").concat(re);if(!j[pe]){var fe=void 0,ve=void 0,ge=void 0,me=void 0,_e=void 0,ye=void 0;switch(p[re]){case 0:fe="solid",ve=a.subarray(f[re],ne?a.length:f[re+1]),ge=l.subarray(v[re],ne?l.length:v[re+1]),_e=A.subarray(m[re],ne?A.length:m[re+1]),ye=c.subarray(_[re],ne?c.length:_[re+1]);break;case 1:fe="surface",ve=a.subarray(f[re],ne?a.length:f[re+1]),ge=l.subarray(v[re],ne?l.length:v[re+1]),_e=A.subarray(m[re],ne?A.length:m[re+1]),ye=c.subarray(_[re],ne?c.length:_[re+1]);break;case 2:fe="points",ve=a.subarray(f[re],ne?a.length:f[re+1]),me=UF(u.subarray(g[re],ne?u.length:g[re+1]));break;case 3:fe="lines",ve=a.subarray(f[re],ne?a.length:f[re+1]),_e=A.subarray(m[re],ne?A.length:m[re+1]);break;default:continue}r.createGeometry({id:pe,primitive:fe,positionsCompressed:ve,normalsCompressed:ge,colors:me,indices:_e,edgeIndices:ye,positionsDecodeMatrix:d}),j[pe]=!0}r.createMesh(le.apply(ee,{id:ce,geometryId:pe,origin:T,matrix:de,color:oe,metallic:ue,roughness:Ae,opacity:ae})),J.push(ce)}else{var be=void 0,we=void 0,Be=void 0,xe=void 0,Pe=void 0,Ce=void 0;switch(p[re]){case 0:be="solid",we=a.subarray(f[re],ne?a.length:f[re+1]),Be=l.subarray(v[re],ne?l.length:v[re+1]),Pe=A.subarray(m[re],ne?A.length:m[re+1]),Ce=c.subarray(_[re],ne?c.length:_[re+1]);break;case 1:be="surface",we=a.subarray(f[re],ne?a.length:f[re+1]),Be=l.subarray(v[re],ne?l.length:v[re+1]),Pe=A.subarray(m[re],ne?A.length:m[re+1]),Ce=c.subarray(_[re],ne?c.length:_[re+1]);break;case 2:be="points",we=a.subarray(f[re],ne?a.length:f[re+1]),xe=UF(u.subarray(g[re],ne?u.length:g[re+1]));break;case 3:be="lines",we=a.subarray(f[re],ne?a.length:f[re+1]),Pe=A.subarray(m[re],ne?A.length:m[re+1]);break;default:continue}r.createMesh(le.apply(ee,{id:ce,origin:T,primitive:be,positionsCompressed:we,normalsCompressed:Be,colors:xe,indices:Pe,edgeIndices:Ce,positionsDecodeMatrix:H,color:oe,metallic:ue,roughness:Ae,opacity:ae})),J.push(ce)}}J.length>0&&r.createEntity(le.apply(q,{id:W,isObject:!0,meshIds:J}))}}}(e,t,a,r,0,n)}},NF=window.pako||pF;NF.inflate||(NF=NF.default);var QF=$.vec4(),VF=$.vec4();var HF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function jF(e){for(var t=[],i=0,r=e.length;i1,ye=me===S-1,be=HF(M.subarray(6*ge,6*ge+3)),we=M[6*ge+3]/255,Be=M[6*ge+4]/255,xe=M[6*ge+5]/255,Pe=n.getNextId();if(_e){var Ce=C[ge],Me=g.slice(Ce,Ce+16),Ee="".concat(o,"-geometry.").concat(J,".").concat(me),Fe=Y[Ee];if(!Fe){Fe={batchThisMesh:!t.reuseGeometries};var ke=!1;switch(_[me]){case 0:Fe.primitiveName="solid",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),Fe.geometryEdgeIndices=v.subarray(x[me],ye?v.length:x[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 1:Fe.primitiveName="surface",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryNormals=d.subarray(b[me],ye?d.length:b[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),Fe.geometryEdgeIndices=v.subarray(x[me],ye?v.length:x[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;case 2:Fe.primitiveName="points",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryColors=jF(p.subarray(w[me],ye?p.length:w[me+1])),ke=Fe.geometryPositions.length>0;break;case 3:Fe.primitiveName="lines",Fe.geometryPositions=h.subarray(y[me],ye?h.length:y[me+1]),Fe.geometryIndices=f.subarray(B[me],ye?f.length:B[me+1]),ke=Fe.geometryPositions.length>0&&Fe.geometryIndices.length>0;break;default:continue}if(ke||(Fe=null),Fe&&(Fe.geometryPositions.length,Fe.batchThisMesh)){Fe.decompressedPositions=new Float32Array(Fe.geometryPositions.length);for(var Ie=Fe.geometryPositions,De=Fe.decompressedPositions,Se=0,Te=Ie.length;Se0&&je.length>0;break;case 1:Ne="surface",Qe=h.subarray(y[me],ye?h.length:y[me+1]),Ve=d.subarray(b[me],ye?d.length:b[me+1]),je=f.subarray(B[me],ye?f.length:B[me+1]),Ge=v.subarray(x[me],ye?v.length:x[me+1]),ze=Qe.length>0&&je.length>0;break;case 2:Ne="points",Qe=h.subarray(y[me],ye?h.length:y[me+1]),He=jF(p.subarray(w[me],ye?p.length:w[me+1])),ze=Qe.length>0;break;case 3:Ne="lines",Qe=h.subarray(y[me],ye?h.length:y[me+1]),je=f.subarray(B[me],ye?f.length:B[me+1]),ze=Qe.length>0&&je.length>0;break;default:continue}ze&&(r.createMesh(le.apply(fe,{id:Pe,origin:K,primitive:Ne,positionsCompressed:Qe,normalsCompressed:Ve,colorsCompressed:He,indices:je,edgeIndices:Ge,positionsDecodeMatrix:re,color:be,metallic:Be,roughness:xe,opacity:we})),he.push(Pe))}}he.length>0&&r.createEntity(le.apply(pe,{id:ae,isObject:!0,meshIds:he}))}}}(e,t,a,r,s,n)}},zF=window.pako||pF;zF.inflate||(zF=zF.default);var WF=$.vec4(),KF=$.vec4();var XF=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();var YF={version:9,parse:function(e,t,i,r,s,n){var o=function(e){return{metadata:e[0],positions:e[1],normals:e[2],colors:e[3],indices:e[4],edgeIndices:e[5],matrices:e[6],reusedGeometriesDecodeMatrix:e[7],eachGeometryPrimitiveType:e[8],eachGeometryPositionsPortion:e[9],eachGeometryNormalsPortion:e[10],eachGeometryColorsPortion:e[11],eachGeometryIndicesPortion:e[12],eachGeometryEdgeIndicesPortion:e[13],eachMeshGeometriesPortion:e[14],eachMeshMatricesPortion:e[15],eachMeshMaterial:e[16],eachEntityId:e[17],eachEntityMeshesPortion:e[18],eachTileAABB:e[19],eachTileEntitiesPortion:e[20]}}(i),a=function(e){function t(e,t){return 0===e.length?[]:zF.inflate(e,t).buffer}return{metadata:JSON.parse(zF.inflate(e.metadata,{to:"string"})),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:JSON.parse(zF.inflate(e.eachEntityId,{to:"string"})),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(o);!function(e,t,i,r,s,n){var o=n.getNextId(),a=i.metadata,l=i.positions,u=i.normals,A=i.colors,c=i.indices,h=i.edgeIndices,d=i.matrices,p=i.reusedGeometriesDecodeMatrix,f=i.eachGeometryPrimitiveType,v=i.eachGeometryPositionsPortion,g=i.eachGeometryNormalsPortion,m=i.eachGeometryColorsPortion,_=i.eachGeometryIndicesPortion,y=i.eachGeometryEdgeIndicesPortion,b=i.eachMeshGeometriesPortion,w=i.eachMeshMatricesPortion,B=i.eachMeshMaterial,x=i.eachEntityId,P=i.eachEntityMeshesPortion,C=i.eachTileAABB,M=i.eachTileEntitiesPortion,E=v.length,F=b.length,k=P.length,I=M.length;s&&s.loadData(a,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds});for(var D=new Uint32Array(E),S=0;S1,ae=ne===E-1,ue=XF(B.subarray(6*se,6*se+3)),Ae=B[6*se+3]/255,ce=B[6*se+4]/255,he=B[6*se+5]/255,de=n.getNextId();if(oe){var pe=w[se],fe=d.slice(pe,pe+16),ve="".concat(o,"-geometry.").concat(O,".").concat(ne),ge=U[ve];if(!ge){ge={batchThisMesh:!t.reuseGeometries};var me=!1;switch(f[ne]){case 0:ge.primitiveName="solid",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 1:ge.primitiveName="surface",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryNormals=u.subarray(g[ne],ae?u.length:g[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),ge.geometryEdgeIndices=h.subarray(y[ne],ae?h.length:y[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;case 2:ge.primitiveName="points",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryColors=A.subarray(m[ne],ae?A.length:m[ne+1]),me=ge.geometryPositions.length>0;break;case 3:ge.primitiveName="lines",ge.geometryPositions=l.subarray(v[ne],ae?l.length:v[ne+1]),ge.geometryIndices=c.subarray(_[ne],ae?c.length:_[ne+1]),me=ge.geometryPositions.length>0&&ge.geometryIndices.length>0;break;default:continue}if(me||(ge=null),ge&&(ge.geometryPositions.length,ge.batchThisMesh)){ge.decompressedPositions=new Float32Array(ge.geometryPositions.length),ge.transformedAndRecompressedPositions=new Uint16Array(ge.geometryPositions.length);for(var _e=ge.geometryPositions,ye=ge.decompressedPositions,be=0,we=_e.length;be0&&Ie.length>0;break;case 1:Me="surface",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Fe=u.subarray(g[ne],ae?u.length:g[ne+1]),Ie=c.subarray(_[ne],ae?c.length:_[ne+1]),De=h.subarray(y[ne],ae?h.length:y[ne+1]),Se=Ee.length>0&&Ie.length>0;break;case 2:Me="points",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),ke=A.subarray(m[ne],ae?A.length:m[ne+1]),Se=Ee.length>0;break;case 3:Me="lines",Ee=l.subarray(v[ne],ae?l.length:v[ne+1]),Ie=c.subarray(_[ne],ae?c.length:_[ne+1]),Se=Ee.length>0&&Ie.length>0;break;default:continue}Se&&(r.createMesh(le.apply(ie,{id:de,origin:L,primitive:Me,positionsCompressed:Ee,normalsCompressed:Fe,colorsCompressed:ke,indices:Ie,edgeIndices:De,positionsDecodeMatrix:G,color:ue,metallic:ce,roughness:he,opacity:Ae})),q.push(de))}}q.length>0&&r.createEntity(le.apply(te,{id:X,isObject:!0,meshIds:q}))}}}(e,t,a,r,s,n)}},JF=window.pako||pF;JF.inflate||(JF=JF.default);var ZF=$.vec4(),qF=$.vec4();var $F=function(){var e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}();function ek(e,t){var i=[];if(t.length>1)for(var r=0,s=t.length-1;r1)for(var n=0,o=e.length/3-1;n0,W=9*V,K=1===A[W+0],X=A[W+1];A[W+2],A[W+3];var Y=A[W+4],J=A[W+5],Z=A[W+6],q=A[W+7],ee=A[W+8];if(z){var te=new Uint8Array(l.subarray(j,G)).buffer,ie="".concat(o,"-texture-").concat(V);if(K)r.createTexture({id:ie,buffers:[te],minFilter:Y,magFilter:J,wrapS:Z,wrapT:q,wrapR:ee});else{var re=new Blob([te],{type:10001===X?"image/jpeg":10002===X?"image/png":"image/gif"}),se=(window.URL||window.webkitURL).createObjectURL(re),ne=document.createElement("img");ne.src=se,r.createTexture({id:ie,image:ne,minFilter:Y,magFilter:J,wrapS:Z,wrapT:q,wrapR:ee})}}}for(var oe=0;oe=0?"".concat(o,"-texture-").concat(Ae):null,normalsTextureId:he>=0?"".concat(o,"-texture-").concat(he):null,metallicRoughnessTextureId:ce>=0?"".concat(o,"-texture-").concat(ce):null,emissiveTextureId:de>=0?"".concat(o,"-texture-").concat(de):null,occlusionTextureId:pe>=0?"".concat(o,"-texture-").concat(pe):null})}for(var fe=new Uint32Array(U),ve=0;ve1,je=Ve===U-1,Ge=F[Qe],ze=Ge>=0?"".concat(o,"-textureSet-").concat(Ge):null,We=$F(k.subarray(6*Qe,6*Qe+3)),Ke=k[6*Qe+3]/255,Xe=k[6*Qe+4]/255,Ye=k[6*Qe+5]/255,Je=n.getNextId();if(He){var Ze=E[Qe],qe=m.slice(Ze,Ze+16),$e="".concat(o,"-geometry.").concat(be,".").concat(Ve),et=ye[$e];if(!et){et={batchThisMesh:!t.reuseGeometries};var tt=!1;switch(y[Ve]){case 0:et.primitiveName="solid",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryNormals=h.subarray(w[Ve],je?h.length:w[Ve+1]),et.geometryUVs=p.subarray(x[Ve],je?p.length:x[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 1:et.primitiveName="surface",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryNormals=h.subarray(w[Ve],je?h.length:w[Ve+1]),et.geometryUVs=p.subarray(x[Ve],je?p.length:x[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),et.geometryEdgeIndices=v.subarray(C[Ve],je?v.length:C[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 2:et.primitiveName="points",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryColors=d.subarray(B[Ve],je?d.length:B[Ve+1]),tt=et.geometryPositions.length>0;break;case 3:et.primitiveName="lines",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryIndices=f.subarray(P[Ve],je?f.length:P[Ve+1]),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;case 4:et.primitiveName="lines",et.geometryPositions=c.subarray(b[Ve],je?c.length:b[Ve+1]),et.geometryIndices=ek(et.geometryPositions,f.subarray(P[Ve],je?f.length:P[Ve+1])),tt=et.geometryPositions.length>0&&et.geometryIndices.length>0;break;default:continue}if(tt||(et=null),et&&(et.geometryPositions.length,et.batchThisMesh)){et.decompressedPositions=new Float32Array(et.geometryPositions.length),et.transformedAndRecompressedPositions=new Uint16Array(et.geometryPositions.length);for(var it=et.geometryPositions,rt=et.decompressedPositions,st=0,nt=it.length;st0&&ft.length>0;break;case 1:At="surface",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),ht=h.subarray(w[Ve],je?h.length:w[Ve+1]),dt=p.subarray(x[Ve],je?p.length:x[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),vt=v.subarray(C[Ve],je?v.length:C[Ve+1]),gt=ct.length>0&&ft.length>0;break;case 2:At="points",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),pt=d.subarray(B[Ve],je?d.length:B[Ve+1]),gt=ct.length>0;break;case 3:At="lines",ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),ft=f.subarray(P[Ve],je?f.length:P[Ve+1]),gt=ct.length>0&&ft.length>0;break;case 4:At="lines",ft=ek(ct=c.subarray(b[Ve],je?c.length:b[Ve+1]),f.subarray(P[Ve],je?f.length:P[Ve+1])),gt=ct.length>0&&ft.length>0;break;default:continue}gt&&(r.createMesh(le.apply(Oe,{id:Je,textureSetId:ze,origin:me,primitive:At,positionsCompressed:ct,normalsCompressed:ht,uv:dt&&dt.length>0?dt:null,colorsCompressed:pt,indices:ft,edgeIndices:vt,positionsDecodeMatrix:Me,color:We,metallic:Xe,roughness:Ye,opacity:Ke})),Le.push(Je))}}Le.length>0&&r.createEntity(le.apply(Ue,{id:Ie,isObject:!0,meshIds:Le}))}}}(e,t,a,r,s,n)}},ik={};ik[mF.version]=mF,ik[bF.version]=bF,ik[xF.version]=xF,ik[MF.version]=MF,ik[kF.version]=kF,ik[TF.version]=TF,ik[OF.version]=OF,ik[GF.version]=GF,ik[YF.version]=YF,ik[tk.version]=tk;var rk=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"XKTLoader",e,s))._maxGeometryBatchSize=s.maxGeometryBatchSize,r.textureTranscoder=s.textureTranscoder,r.dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r.includeTypes=s.includeTypes,r.excludeTypes=s.excludeTypes,r.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,r.reuseGeometries=s.reuseGeometries,r}return C(i,[{key:"supportedVersions",get:function(){return Object.keys(ik)}},{key:"textureTranscoder",get:function(){return this._textureTranscoder},set:function(e){this._textureTranscoder=e}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new dF}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"reuseGeometries",get:function(){return this._reuseGeometries},set:function(e){this._reuseGeometries=!1!==e}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id),!(t.src||t.xkt||t.manifestSrc||t.manifest))return this.error("load() param expected: src, xkt, manifestSrc or manifestData"),A;var i={},r=t.includeTypes||this._includeTypes,s=t.excludeTypes||this._excludeTypes,n=t.objectDefaults||this._objectDefaults;if(i.reuseGeometries=null!==t.reuseGeometries&&void 0!==t.reuseGeometries?t.reuseGeometries:!1!==this._reuseGeometries,r){i.includeTypesMap={};for(var o=0,a=r.length;o=t.length?n():e._dataSource.getMetaModel("".concat(m).concat(t[a]),(function(t){h.loadData(t,{includeTypes:r,excludeTypes:s,globalizeObjectIds:i.globalizeObjectIds}),a++,e.scheduleTask(l,100)}),o)}()},y=function(r,s,n){var o=0;!function a(){o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,A,null,v),o++,e.scheduleTask(a,100)}),n)}()},b=function(r,s,n){var o=0;!function a(){o>=r.length?s():e._dataSource.getXKT("".concat(m).concat(r[o]),(function(r){e._parseModel(r,t,i,A,h,v),o++,e.scheduleTask(a,100)}),n)}()};if(t.manifest){var w=t.manifest,B=w.xktFiles;if(!B||0===B.length)return void p("load(): Failed to load model manifest - manifest not valid");var x=w.metaModelFiles;x?_(x,(function(){y(B,d,p)}),p):b(B,d,p)}else this._dataSource.getManifest(t.manifestSrc,(function(e){if(!A.destroyed){var t=e.xktFiles;if(t&&0!==t.length){var i=e.metaModelFiles;i?_(i,(function(){y(t,d,p)}),p):b(t,d,p)}else p("load(): Failed to load model manifest - manifest not valid")}}),p)}return A}},{key:"_loadModel",value:function(e,t,i,r,s,n,o,a){var l=this;this._dataSource.getXKT(t.src,(function(e){l._parseModel(e,t,i,r,s,n),o()}),a)}},{key:"_parseModel",value:function(e,t,i,r,s,n){if(!r.destroyed){var o=new DataView(e),a=new Uint8Array(e),l=o.getUint32(0,!0),u=ik[l];if(u){this.log("Loading .xkt V"+l);for(var A=o.getUint32(4,!0),c=[],h=4*(A+2),d=0;de.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){s(e)}}}function p(){}function f(e){var i,r=this;r.init=function(e){i=new Blob([],{type:o}),e()},r.writeUint8Array=function(e,r){i=new Blob([i,t?e:e.buffer],{type:o}),r()},r.getData=function(t,r){var s=new FileReader;s.onload=function(e){t(e.target.result)},s.onerror=r,s.readAsText(i,e)}}function v(t){var i=this,r="",s="";i.init=function(e){r+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var n,o=s.length,a=s;for(s="",n=0;n<3*Math.floor((o+t.length)/3)-o;n++)a+=String.fromCharCode(t[n]);for(;n2?r+=e.btoa(a):s=a,i()},i.getData=function(t){t(r+e.btoa(s))}}function g(e){var i,r=this;r.init=function(t){i=new Blob([],{type:e}),t()},r.writeUint8Array=function(r,s){i=new Blob([i,t?r:r.buffer],{type:e}),s()},r.getData=function(e){e(i)}}function m(e,t,i,r,s,o,a,l,u,A){var c,h,d,p=0,f=t.sn;function v(){e.removeEventListener("message",g,!1),l(h,d)}function g(t){var i=t.data,s=i.data,n=i.error;if(n)return n.toString=function(){return"Error: "+this.message},void u(n);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":s?(h+=s.length,r.writeUint8Array(s,(function(){m()}),A)):m();break;case"flush":d=i.crc,s?(h+=s.length,r.writeUint8Array(s,(function(){v()}),A)):v();break;case"progress":a&&a(c+i.loaded,o);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function m(){(c=p*n)<=o?i.readUint8Array(s+c,Math.min(n,o-c),(function(i){a&&a(c,o);var r=0===c?t:{sn:f};r.type="append",r.data=i;try{e.postMessage(r,[i.buffer])}catch(t){e.postMessage(r)}p++}),u):e.postMessage({sn:f,type:"flush"})}h=0,e.addEventListener("message",g,!1),m()}function _(e,t,i,r,s,o,l,u,A,c){var h,d=0,p=0,f="input"===o,v="output"===o,g=new a;!function o(){var a;if((h=d*n)127?s[i-128]:String.fromCharCode(i);return r}function w(e){return decodeURIComponent(escape(e))}function B(e){var t,i="";for(t=0;t>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((r||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):s("File is using Zip64 (4gb+ file size).")):s("File contains encrypted entry.")}function P(t,n,o){var a=0;function l(){}l.prototype.getData=function(r,n,l,A){var c=this;function h(e,t){A&&!function(e){var t=u(4);return t.view.setUint32(0,e),c.crc32==t.view.getUint32(0)}(t)?o("CRC failed."):r.getData((function(e){n(e)}))}function d(e){o(e||s)}function p(e){o(e||"Error while writing file data.")}t.readUint8Array(c.offset,30,(function(s){var n,f=u(s.length,s);1347093252==f.view.getUint32(0)?(x(c,f,4,!1,o),n=c.offset+30+c.filenameLength+c.extraFieldLength,r.init((function(){0===c.compressionMethod?y(c._worker,a++,t,r,n,c.compressedSize,A,h,l,d,p):function(t,i,r,s,n,o,a,l,u,A,c){var h=a?"output":"none";e.zip.useWebWorkers?m(t,{sn:i,codecClass:"Inflater",crcType:h},r,s,n,o,u,l,A,c):_(new e.zip.Inflater,r,s,n,o,h,u,l,A,c)}(c._worker,a++,t,r,n,c.compressedSize,A,h,l,d,p)}),p)):o(i)}),d)};var A={getEntries:function(e){var s=this._worker;!function(e){t.size<22?o(i):s(22,(function(){s(Math.min(65558,t.size),(function(){o(i)}))}));function s(i,s){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));s()}),(function(){o(r)}))}}((function(n){var a,A;a=n.getUint32(16,!0),A=n.getUint16(8,!0),a<0||a>=t.size?o(i):t.readUint8Array(a,t.size-a,(function(t){var r,n,a,c,h=0,d=[],p=u(t.length,t);for(r=0;r>>8^i[255&(t^e[r])];this.crc=t},a.prototype.get=function(){return~this.crc},a.prototype.table=function(){var e,t,i,r=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;r[e]=i}return r}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},c.prototype=new A,c.prototype.constructor=c,h.prototype=new A,h.prototype.constructor=h,d.prototype=new A,d.prototype.constructor=d,p.prototype.getData=function(e){e(this.data)},f.prototype=new p,f.prototype.constructor=f,v.prototype=new p,v.prototype.constructor=v,g.prototype=new p,g.prototype.constructor=g;var F={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function k(t,i,r){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var s;if(e.zip.workerScripts){if(s=e.zip.workerScripts[t],!Array.isArray(s))return void r(new Error("zip.workerScripts."+t+" is not an array!"));s=function(e){var t=document.createElement("a");return e.map((function(e){return t.href=e,t.href}))}(s)}else(s=F[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+s[0];var n=new Worker(s[0]);n.codecTime=n.crcTime=0,n.postMessage({type:"importScripts",scripts:s.slice(1)}),n.addEventListener("message",(function e(t){var s=t.data;if(s.error)return n.terminate(),void r(s.error);"importScripts"===s.type&&(n.removeEventListener("message",e),n.removeEventListener("error",o),i(n))})),n.addEventListener("error",o)}else r(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function o(e){n.terminate(),r(e)}}function I(e){console.error(e)}e.zip={Reader:A,Writer:p,BlobReader:d,Data64URIReader:h,TextReader:c,BlobWriter:g,Data64URIWriter:v,TextWriter:f,createReader:function(e,t,i){i=i||I,e.init((function(){P(e,t,i)}),i)},createWriter:function(e,t,i,r){i=i||I,r=!!r,e.init((function(){E(e,t,i,r)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(nk);var ok=nk.zip;!function(e){var t,i,r=e.Reader,s=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function n(e){var t=this;function i(i,r){var s;t.data?i():((s=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(s.getResponseHeader("Content-Length"))||Number(s.response.byteLength)),t.data=new Uint8Array(s.response),i()}),!1),s.addEventListener("error",r,!1),s.open("GET",e),s.responseType="arraybuffer",s.send())}t.size=0,t.init=function(r,s){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var n=new XMLHttpRequest;n.addEventListener("load",(function(){t.size=Number(n.getResponseHeader("Content-Length")),t.size?r():i(r,s)}),!1),n.addEventListener("error",s,!1),n.open("HEAD",e),n.send()}else i(r,s)},t.readUint8Array=function(e,r,s,n){i((function(){s(new Uint8Array(t.data.subarray(e,e+r)))}),n)}}function o(e){var t=this;t.size=0,t.init=function(i,r){var s=new XMLHttpRequest;s.addEventListener("load",(function(){t.size=Number(s.getResponseHeader("Content-Length")),"bytes"==s.getResponseHeader("Accept-Ranges")?i():r("HTTP Range not supported.")}),!1),s.addEventListener("error",r,!1),s.open("HEAD",e),s.send()},t.readUint8Array=function(t,i,r,s){!function(t,i,r,s){var n=new XMLHttpRequest;n.open("GET",e),n.responseType="arraybuffer",n.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),n.addEventListener("load",(function(){r(n.response)}),!1),n.addEventListener("error",s,!1),n.send()}(t,i,(function(e){r(new Uint8Array(e))}),s)}}function a(e){var t=this;t.size=0,t.init=function(i,r){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,r,s){r(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,r){var s=new Uint8Array(e.length+t.length);s.set(e),s.set(t,e.length),e=s,i()},t.getData=function(t){t(e.buffer)}}function u(e,t){var r,s=this;s.init=function(t,i){e.createWriter((function(e){r=e,t()}),i)},s.writeUint8Array=function(e,s,n){var o=new Blob([i?e:e.buffer],{type:t});r.onwrite=function(){r.onwrite=null,s()},r.onerror=n,r.write(o)},s.getData=function(t){e.file(t)}}n.prototype=new r,n.prototype.constructor=n,o.prototype=new r,o.prototype.constructor=o,a.prototype=new r,a.prototype.constructor=a,l.prototype=new s,l.prototype.constructor=l,u.prototype=new s,u.prototype.constructor=u,e.FileWriter=u,e.HttpReader=n,e.HttpRangeReader=o,e.ArrayBufferReader=a,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(i,r,s){return function(i,r,s,n){if(i.directory)return n?new t(i.fs,r,s,i):new e.fs.ZipFileEntry(i.fs,r,s,i);throw"Parent entry is not a directory."}(this,i,{data:r,Reader:s?o:n})},t.prototype.importHttpContent=function(e,t,i,r){this.importZip(t?new o(e):new n(e),i,r)},e.fs.FS.prototype.importHttpContent=function(e,i,r,s){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,r,s)})}(ok);var ak=["4.2"],lk=function(){function e(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};x(this,e),this.supportedSchemas=ak,this._xrayOpacity=.7,this._src=null,this._options=i,this.viewpoint=null,i.workerScriptsPath?(ok.workerScriptsPath=i.workerScriptsPath,this.src=i.src,this.xrayOpacity=.7,this.displayEffect=i.displayEffect,this.createMetaModel=i.createMetaModel):t.error("Config expected: workerScriptsPath")}return C(e,[{key:"load",value:function(e,t,i,r,s,n){switch(r.materialType){case"MetallicMaterial":t._defaultMaterial=new Cn(t,{baseColor:[1,1,1],metallic:.6,roughness:.6});break;case"SpecularMaterial":t._defaultMaterial=new Fn(t,{diffuse:[1,1,1],specular:$.vec3([1,1,1]),glossiness:.5});break;default:t._defaultMaterial=new Ni(t,{reflectivity:.75,shiness:100,diffuse:[1,1,1]})}t._wireframeMaterial=new Bn(t,{color:[0,0,0],lineWidth:2});var o=t.scene.canvas.spinner;o.processes++,uk(e,t,i,r,(function(){o.processes--,s&&s(),t.fire("loaded",!0,!1)}),(function(e){o.processes--,t.error(e),n&&n(e),t.fire("error",e)}),(function(e){console.log("Error, Will Robinson: "+e)}))}}]),e}(),uk=function(e,t,i,r,s,n){!function(e,t,i){var r=new gk;r.load(e,(function(){t(r)}),(function(e){i("Error loading ZIP archive: "+e)}))}(i,(function(i){Ak(e,i,r,t,s,n)}),n)},Ak=function(){return function(t,i,r,s,n){var o={plugin:t,zip:i,edgeThreshold:30,materialType:r.materialType,scene:s.scene,modelNode:s,info:{references:{}},materials:{}};r.createMetaModel&&(o.metaModelData={modelId:s.id,metaObjects:[{name:s.id,type:"Default",id:s.id}]}),s.scene.loading++,function(t,i){t.zip.getFile("Manifest.xml",(function(r,s){for(var n=s.children,o=0,a=n.length;o0){for(var o=n.trim().split(" "),a=new Int16Array(o.length),l=0,u=0,A=o.length;u0){i.primitive="triangles";for(var n=[],o=0,a=s.length;o=t.length)i();else{var a=t[n].id,l=a.lastIndexOf(":");l>0&&(a=a.substring(l+1));var u=a.lastIndexOf("#");u>0&&(a=a.substring(0,u)),r[a]?s(n+1):function(e,t,i){e.zip.getFile(t,(function(t,r){!function(e,t,i){for(var r,s=t.children,n=0,o=s.length;n0)for(var r=0,s=t.length;r1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),r=t.call(this,"XML3DLoader",e,s),s.workerScriptsPath?(r._workerScriptsPath=s.workerScriptsPath,r._loader=new lk(b(r),s),r.supportedSchemas=r._loader.supportedSchemas,r):(r.error("Config expected: workerScriptsPath"),y(r))}return C(i,[{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.workerScriptsPath=this._workerScriptsPath,e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new wn(this.viewer.scene,le.apply(e,{isModel:!0})),i=e.src;return i?(this._loader.load(this,t,i,e),t):(this.error("load() param expected: src"),t)}}]),i}(),yk=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getIFC",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,"ifcLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r.includeTypes=s.includeTypes,r.excludeTypes=s.excludeTypes,r.excludeUnclassifiedObjects=s.excludeUnclassifiedObjects,!s.WebIFC)throw"Parameter expected: WebIFC";if(!s.IfcAPI)throw"Parameter expected: IfcAPI";return r._webIFC=s.WebIFC,r._ifcAPI=s.IfcAPI,r}return C(i,[{key:"supportedVersions",get:function(){return["2x3","4"]}},{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new yk}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"includeTypes",get:function(){return this._includeTypes},set:function(e){this._includeTypes=e}},{key:"excludeTypes",get:function(){return this._excludeTypes},set:function(e){this._excludeTypes=e}},{key:"excludeUnclassifiedObjects",get:function(){return this._excludeUnclassifiedObjects},set:function(e){this._excludeUnclassifiedObjects=!!e}},{key:"globalizeObjectIds",get:function(){return this._globalizeObjectIds},set:function(e){this._globalizeObjectIds=!!e}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new hh(this.viewer.scene,le.apply(e,{isModel:!0}));if(!e.src&&!e.ifc)return this.error("load() param expected: src or IFC"),t;var i={autoNormals:!0};if(!1!==e.loadMetadata){var r=e.includeTypes||this._includeTypes,s=e.excludeTypes||this._excludeTypes,n=e.objectDefaults||this._objectDefaults;if(r){i.includeTypesMap={};for(var o=0,a=r.length;o0){for(var l=n.Name.value,u=[],A=0,c=a.length;A0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getLAS",value:function(e,t,i){e=this._cacheBusterURL(e);var r=function(){};t=t||r,i=i||r;var s=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(s){var n=!!s[2],o=s[3];o=window.decodeURIComponent(o),n&&(o=window.atob(o));try{for(var a=new ArrayBuffer(o.length),l=new Uint8Array(a),u=0;u1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"lasLoader",e,s)).dataSource=s.dataSource,r.skip=s.skip,r.fp64=s.fp64,r.colorDepth=s.colorDepth,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new wk}},{key:"skip",get:function(){return this._skip},set:function(e){this._skip=e||1}},{key:"fp64",get:function(){return this._fp64},set:function(e){this._fp64=!!e}},{key:"colorDepth",get:function(){return this._colorDepth},set:function(e){this._colorDepth=e||"auto"}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0}));if(!t.src&&!t.las)return this.error("load() param expected: src or las"),i;var r={las:{skip:this._skip,fp64:this._fp64,colorDepth:this._colorDepth}};if(t.src)this._loadModel(t.src,t,r,i);else{var s=this.viewer.scene.canvas.spinner;s.processes++,this._parseModel(t.las,t,r,i).then((function(){s.processes--}),(function(t){s.processes--,e.error(t),i.fire("error",t)}))}return i}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getLAS(t.src,(function(e){s._parseModel(e,t,i,r).then((function(){n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){var s=this;function n(e){var i=e.value;if(t.rotateX&&i)for(var r=0,s=i.length;r=e.length)return[e];for(var i=[],r=0;r0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getCityJSON",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}();function Dk(e,t,i){i=i||2;var r,s,n,o,a,l,u,A=t&&t.length,c=A?t[0]*i:e.length,h=Sk(e,0,c,i,!0),d=[];if(!h||h.next===h.prev)return d;if(A&&(h=function(e,t,i,r){var s,n,o,a=[];for(s=0,n=t.length;s80*i){r=n=e[0],s=o=e[1];for(var p=i;pn&&(n=a),l>o&&(o=l);u=0!==(u=Math.max(n-r,o-s))?1/u:0}return Lk(h,d,i,r,s,u),d}function Sk(e,t,i,r,s){var n,o;if(s===rI(e,t,i,r)>0)for(n=t;n=t;n-=r)o=eI(n,e[n],e[n+1],o);return o&&Xk(o,o.next)&&(tI(o),o=o.next),o}function Tk(e,t){if(!e)return e;t||(t=e);var i,r=e;do{if(i=!1,r.steiner||!Xk(r,r.next)&&0!==Kk(r.prev,r,r.next))r=r.next;else{if(tI(r),(r=t=r.prev)===r.next)break;i=!0}}while(i||r!==t);return t}function Lk(e,t,i,r,s,n,o){if(e){!o&&n&&function(e,t,i,r){var s=e;do{null===s.z&&(s.z=jk(s.x,s.y,t,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==e);s.prevZ.nextZ=null,s.prevZ=null,function(e){var t,i,r,s,n,o,a,l,u=1;do{for(i=e,e=null,n=null,o=0;i;){for(o++,r=i,a=0,t=0;t0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;i=r}n.nextZ=null,u*=2}while(o>1)}(s)}(e,r,s,n);for(var a,l,u=e;e.prev!==e.next;)if(a=e.prev,l=e.next,n?Uk(e,r,s,n):Rk(e))t.push(a.i/i),t.push(e.i/i),t.push(l.i/i),tI(e),e=l.next,u=l.next;else if((e=l)===u){o?1===o?Lk(e=Ok(Tk(e),t,i),t,i,r,s,n,2):2===o&&Nk(e,t,i,r,s,n):Lk(Tk(e),t,i,r,s,n,1);break}}}function Rk(e){var t=e.prev,i=e,r=e.next;if(Kk(t,i,r)>=0)return!1;for(var s=e.next.next;s!==e.prev;){if(zk(t.x,t.y,i.x,i.y,r.x,r.y,s.x,s.y)&&Kk(s.prev,s,s.next)>=0)return!1;s=s.next}return!0}function Uk(e,t,i,r){var s=e.prev,n=e,o=e.next;if(Kk(s,n,o)>=0)return!1;for(var a=s.xn.x?s.x>o.x?s.x:o.x:n.x>o.x?n.x:o.x,A=s.y>n.y?s.y>o.y?s.y:o.y:n.y>o.y?n.y:o.y,c=jk(a,l,t,i,r),h=jk(u,A,t,i,r),d=e.prevZ,p=e.nextZ;d&&d.z>=c&&p&&p.z<=h;){if(d!==e.prev&&d!==e.next&&zk(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&Kk(d.prev,d,d.next)>=0)return!1;if(d=d.prevZ,p!==e.prev&&p!==e.next&&zk(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&Kk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(;d&&d.z>=c;){if(d!==e.prev&&d!==e.next&&zk(s.x,s.y,n.x,n.y,o.x,o.y,d.x,d.y)&&Kk(d.prev,d,d.next)>=0)return!1;d=d.prevZ}for(;p&&p.z<=h;){if(p!==e.prev&&p!==e.next&&zk(s.x,s.y,n.x,n.y,o.x,o.y,p.x,p.y)&&Kk(p.prev,p,p.next)>=0)return!1;p=p.nextZ}return!0}function Ok(e,t,i){var r=e;do{var s=r.prev,n=r.next.next;!Xk(s,n)&&Yk(s,r,r.next,n)&&qk(s,n)&&qk(n,s)&&(t.push(s.i/i),t.push(r.i/i),t.push(n.i/i),tI(r),tI(r.next),r=e=n),r=r.next}while(r!==e);return Tk(r)}function Nk(e,t,i,r,s,n){var o=e;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&Wk(o,a)){var l=$k(o,a);return o=Tk(o,o.next),l=Tk(l,l.next),Lk(o,t,i,r,s,n),void Lk(l,t,i,r,s,n)}a=a.next}o=o.next}while(o!==e)}function Qk(e,t){return e.x-t.x}function Vk(e,t){if(t=function(e,t){var i,r=t,s=e.x,n=e.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o){if(o=a,a===s){if(n===r.y)return r;if(n===r.next.y)return r.next}i=r.x=r.x&&r.x>=A&&s!==r.x&&zk(ni.x||r.x===i.x&&Hk(i,r)))&&(i=r,h=l)),r=r.next}while(r!==u);return i}(e,t),t){var i=$k(t,e);Tk(t,t.next),Tk(i,i.next)}}function Hk(e,t){return Kk(e.prev,e,t.prev)<0&&Kk(t.next,e,e.next)<0}function jk(e,t,i,r,s){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-i)*s)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-r)*s)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Gk(e){var t=e,i=e;do{(t.x=0&&(e-o)*(r-a)-(i-o)*(t-a)>=0&&(i-o)*(n-a)-(s-o)*(r-a)>=0}function Wk(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Yk(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(qk(e,t)&&qk(t,e)&&function(e,t){var i=e,r=!1,s=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==e);return r}(e,t)&&(Kk(e.prev,e,t.prev)||Kk(e,t.prev,t))||Xk(e,t)&&Kk(e.prev,e,e.next)>0&&Kk(t.prev,t,t.next)>0)}function Kk(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Xk(e,t){return e.x===t.x&&e.y===t.y}function Yk(e,t,i,r){var s=Zk(Kk(e,t,i)),n=Zk(Kk(e,t,r)),o=Zk(Kk(i,r,e)),a=Zk(Kk(i,r,t));return s!==n&&o!==a||(!(0!==s||!Jk(e,i,t))||(!(0!==n||!Jk(e,r,t))||(!(0!==o||!Jk(i,e,r))||!(0!==a||!Jk(i,t,r)))))}function Jk(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Zk(e){return e>0?1:e<0?-1:0}function qk(e,t){return Kk(e.prev,e,e.next)<0?Kk(e,t,e.next)>=0&&Kk(e,e.prev,t)>=0:Kk(e,t,e.prev)<0||Kk(e,e.next,t)<0}function $k(e,t){var i=new iI(e.i,e.x,e.y),r=new iI(t.i,t.x,t.y),s=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function eI(e,t,i,r){var s=new iI(e,t,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function tI(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function iI(e,t,i){this.i=e,this.x=t,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1}function rI(e,t,i,r){for(var s=0,n=t,o=i-r;n0&&(r+=e[s-1].length,i.holes.push(r))}return i};var sI=$.vec2(),nI=$.vec3(),oI=$.vec3(),aI=$.vec3(),lI=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"cityJSONLoader",e,s)).dataSource=s.dataSource,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new Ik}},{key:"load",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);var t=new hh(this.viewer.scene,le.apply(e,{isModel:!0,edges:!0}));if(!e.src&&!e.cityJSON)return this.error("load() param expected: src or cityJSON"),t;var i={};if(e.src)this._loadModel(e.src,e,i,t);else{var r=this.viewer.scene.canvas.spinner;r.processes++,this._parseModel(e.cityJSON,e,i,t),r.processes--}return t}},{key:"_loadModel",value:function(e,t,i,r){var s=this,n=this.viewer.scene.canvas.spinner;n.processes++,this._dataSource.getCityJSON(t.src,(function(e){s._parseModel(e,t,i,r),n.processes--}),(function(e){n.processes--,s.error(e),r.fire("error",e)}))}},{key:"_parseModel",value:function(e,t,i,r){if(!r.destroyed){var s=e.transform?this._transformVertices(e.vertices,e.transform,i.rotateX):e.vertices,n=t.stats||{};n.sourceFormat=e.type||"CityJSON",n.schemaVersion=e.version||"",n.title="",n.author="",n.created="",n.numMetaObjects=0,n.numPropertySets=0,n.numObjects=0,n.numGeometries=0,n.numTriangles=0,n.numVertices=0;var o=!1!==t.loadMetadata,a=o?{id:$.createUUID(),name:"Model",type:"Model"}:null,l=o?{id:"",projectId:"",author:"",createdAt:"",schema:e.version||"",creatingApplication:"",metaObjects:[a],propertySets:[]}:null,u={data:e,vertices:s,sceneModel:r,loadMetadata:o,metadata:l,rootMetaObject:a,nextId:0,stats:n};if(this._parseCityJSON(u),r.finalize(),o){var A=r.id;this.viewer.metaScene.createMetaModel(A,u.metadata,i)}r.scene.once("tick",(function(){r.destroyed||(r.scene.fire("modelLoaded",r.id),r.fire("loaded",!0,!1))}))}}},{key:"_transformVertices",value:function(e,t,i){for(var r=[],s=t.scale||$.vec3([1,1,1]),n=t.translate||$.vec3([0,0,0]),o=0,a=0;o0){for(var u=[],A=0,c=t.geometry.length;A0){var _=g[m[0]];if(void 0!==_.value)d=v[_.value];else{var y=_.values;if(y){p=[];for(var b=0,w=y.length;b0&&(r.createEntity({id:i,meshIds:u,isObject:!0}),e.stats.numObjects++)}}},{key:"_parseGeometrySurfacesWithOwnMaterials",value:function(e,t,i,r){switch(t.type){case"MultiPoint":case"MultiLineString":break;case"MultiSurface":case"CompositeSurface":var s=t.boundaries;this._parseSurfacesWithOwnMaterials(e,i,s,r);break;case"Solid":for(var n=t.boundaries,o=0;o0&&c.push(u.length);var f=this._extractLocalIndices(e,a[p],h,d);u.push.apply(u,A(f))}if(3===u.length)d.indices.push(u[0]),d.indices.push(u[1]),d.indices.push(u[2]);else if(u.length>3){for(var v=[],g=0;g0&&o.indices.length>0){var f=""+e.nextId++;s.createMesh({id:f,primitive:"triangles",positions:o.positions,indices:o.indices,color:i&&i.diffuseColor?i.diffuseColor:[.8,.8,.8],opacity:1}),r.push(f),e.stats.numGeometries++,e.stats.numVertices+=o.positions.length/3,e.stats.numTriangles+=o.indices.length/3}}},{key:"_parseSurfacesWithSharedMaterial",value:function(e,t,i,r){for(var s=e.vertices,n=0;n0&&a.push(o.length);var u=this._extractLocalIndices(e,t[n][l],i,r);o.push.apply(o,A(u))}if(3===o.length)r.indices.push(o[0]),r.indices.push(o[1]),r.indices.push(o[2]);else if(o.length>3){for(var c=[],h=0;h0&&void 0!==arguments[0]?arguments[0]:{};x(this,e),this.cacheBuster=!1!==t.cacheBuster}return C(e,[{key:"_cacheBusterURL",value:function(e){if(!this.cacheBuster)return e;var t=(new Date).getTime();return e.indexOf("?")>-1?e+"&_="+t:e+"?_="+t}},{key:"getDotBIM",value:function(e,t,i){le.loadJSON(this._cacheBusterURL(e),(function(e){t(e)}),(function(e){i(e)}))}}]),e}(),AI=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"DotBIMLoader",e,s)).dataSource=s.dataSource,r.objectDefaults=s.objectDefaults,r}return C(i,[{key:"dataSource",get:function(){return this._dataSource},set:function(e){this._dataSource=e||new uI}},{key:"objectDefaults",get:function(){return this._objectDefaults},set:function(e){this._objectDefaults=e||AE}},{key:"load",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.id&&this.viewer.scene.components[t.id]&&(this.error("Component with this ID already exists in viewer: "+t.id+" - will autogenerate this ID"),delete t.id);var i=new hh(this.viewer.scene,le.apply(t,{isModel:!0,backfaces:t.backfaces,dtxEnabled:t.dtxEnabled,rotation:t.rotation,origin:t.origin})),r=i.id;if(!t.src&&!t.dotBIM)return this.error("load() param expected: src or dotBIM"),i;var s,n,o=t.objectDefaults||this._objectDefaults||AE;if(t.includeTypes){s={};for(var a=0,l=t.includeTypes.length;a=0?A:2*Math.PI-A}return s0||o>0||a>0))}}(),n=[],o=(r?t:t.slice(0).reverse()).map((function(e){return{idx:e}}));o.forEach((function(e,t){e.prev=o[(t-1+o.length)%o.length],e.next=o[(t+1)%o.length]}));for(var a=$.vec2(),l=$.vec2();o.length>2;){for(var u=0,A=function(){if(u>=o.length)throw"isCCW = ".concat(r,"; earIdx = ").concat(u,"; len = ").concat(o.length);var t=o[u],i=e[t.prev.idx],n=e[t.idx],A=e[t.next.idx];if($.subVec2(i,n,a),$.subVec2(A,n,l),a[0]*l[1]-a[1]*l[0]>=0&&o.every((function(r){return r===t||r===t.prev||r===t.next||!s(e[r.idx],i,n,A)})))return"break";++u};;){if("break"===A())break}var c=o[u];o.splice(u,1),n.push([c.idx,c.next.idx,c.prev.idx]),c.prev.next=c.next,c.next.prev=c.prev}return[e,n]},pI=function(e,t,i,r,s,n,o,a,l){var u,c=i.scene,h=c.canvas.canvas,d=new et(c,{}),p=function(e){var t=$.vec2([e.clientX,e.clientY]);hI(h.ownerDocument.body,h,t);var i=function(e){var t=$.vec3(),i=$.vec3();return $.canvasPosToWorldRay(h,c.camera.viewMatrix,c.camera.projMatrix,e,t,i),n(t,i)}(t);d.worldPos=i,B(),a(t,i)},f=null,v=function(e){var t=f.matchesEvent(e);t&&p(t)},g=function(e){var t=f.matchesEvent(e);t&&(b.setOpacity(w),f.cleanup(),p(t),l())},m=function(e,t){f&&f.cleanup(),b.setOpacity(1),b.setClickable(!1),i.cameraControl.active=!1,f={matchesEvent:e,cleanup:function(){f=null,b.setClickable(!0),i.cameraControl.active=!0,t()}},o()},_={fillColor:s};(e&&(_.onMouseOver=function(){return!f&&b.setOpacity(1)},_.onMouseLeave=function(){return!f&&b.setOpacity(w)},_.onMouseDown=function(e){1===e.which&&(h.addEventListener("mousemove",v),h.addEventListener("mouseup",g),m((function(e){return 1===e.which&&e}),(function(){h.removeEventListener("mousemove",v),h.removeEventListener("mouseup",g)})))}),t)&&(_.onTouchstart=function(e){e.preventDefault(),1===e.touches.length&&(u=e.touches[0].identifier,m((function(e){return A(e.changedTouches).find((function(e){return e.identifier===u}))}),(function(){u=null})))},_.onTouchmove=function(e){e.preventDefault(),v(e)},_.onTouchend=function(e){e.preventDefault(),g(e)});var y=h.ownerDocument.body,b=new rt(y,_),w=.5;b.setOpacity(w);var B=function(){var e=d.canvasPos.slice();hI(h,y,e),b.setPos(e[0],e[1])};d.worldPos=r,B();var x=c.camera.on("viewMatrix",B),P=c.camera.on("projMatrix",B);return{setActive:function(e){return b.setClickable(e)},getWorldPos:function(){return d.worldPos},setWorldPos:function(e){d.worldPos=e,B()},destroy:function(){f&&f.cleanup(),c.camera.off(x),c.camera.off(P),d.destroy(),b.destroy()}}},fI=function(e,t){var i=e.canvas.canvas,r=i.parentNode,s=document.createElement("div");r.insertBefore(s,i);var n=5;s.style.background=t,s.style.border="2px solid white",s.style.margin="0 0",s.style.zIndex="100",s.style.position="absolute",s.style.pointerEvents="none",s.style.display="none";var o=new et(e,{}),a=function(e){return e+"px"},l=function(){var e=o.canvasPos.slice();hI(i,r,e),s.style.left=a(e[0]-3-n/2),s.style.top=a(e[1]-3-n/2),s.style.borderRadius=a(2*n),s.style.width=a(n),s.style.height=a(n)},u=e.camera.on("viewMatrix",l),A=e.camera.on("projMatrix",l);return{update:function(e){e&&(o.worldPos=e,l()),s.style.display=e?"":"none"},setHighlighted:function(e){n=e?10:5,l()},getCanvasPos:function(){return o.canvasPos},getWorldPos:function(){return o.worldPos},destroy:function(){s.parentNode.removeChild(s),e.camera.off(u),e.camera.off(A),o.destroy()}}},vI=function(e,t,i){var r=null,s=function(s){if(s){r&&r.destroy();try{var n,o,a=dI(s.map((function(e){return[e[0],e[2]]}))),l=h(a,2),u=l[0],c=l[1],d=(n=[]).concat.apply(n,A(u.map((function(e){return[e[0],s[0][1],e[1]]})))),p=(o=[]).concat.apply(o,A(c));r=new nn(e,{pickable:!1,geometry:new Ti(e,{positions:d,indices:p,normals:$.buildNormals(d,p)}),material:new Ni(e,{alpha:void 0!==i?i:.5,backfaces:!0,diffuse:cI(t)})})}catch(e){r=null}}r&&(r.visible=!!s)};return s(null),{updateBase:s,destroy:function(){return r&&r.destroy()}}},gI=function(e,t,i,r,s,n,o,a,l){var u=fI(e,r),A=fI(e,r),c=vI(e,r,s),h=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},d=a((function(){h(null),u.update(null)}),(function(e,t){h(e),u.update(t)}),(function(e,n){u.update(n),d=a((function(){h(null),A.update(null),c.updateBase(null)}),(function(e,t){if(h(e),A.update(t),$.distVec3(n,t)>.01){var i=function(e){return Math.min(n[e],t[e])},r=function(e){return Math.max(n[e],t[e])},s=i(0),o=i(1),a=i(2),l=r(0);r(1);var u=r(2);c.updateBase([[s,o,u],[l,o,u],[l,o,a],[s,o,a]])}else c.updateBase(null)}),(function(e,a){A.update(a),u.destroy(),A.destroy(),c.destroy(),h(null);var d=function(e){return Math.min(n[e],a[e])},p=function(e){return Math.max(n[e],a[e])},f=d(0),v=d(2),g=p(0),m=p(2),_=o.createZone({id:$.createUUID(),geometry:{planeCoordinates:[[f,m],[g,m],[g,v],[f,v]],altitude:t,height:i},alpha:s,color:r});l(_)}))}));return{deactivate:function(){d(),u.destroy(),A.destroy(),c.destroy(),h(null)}}},mI=function(e,t){return function(i,r,s){var n=e.scene,o=n.canvas.canvas,a=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(o.ownerDocument.body,o,t),t},l=function(e){var i=$.vec3(),r=$.vec3();return $.canvasPosToWorldRay(o,n.camera.viewMatrix,n.camera.projMatrix,e,i,r),t(i,r)},u=!1,A=function(){u=!1},c=function(){A(),o.removeEventListener("mousedown",d),o.removeEventListener("mousemove",p),e.cameraControl.off(f),o.removeEventListener("mouseup",v)},h=$.vec2(),d=function(e){1===e.which&&(a(e,h),u=!0)};o.addEventListener("mousedown",d);var p=function(e){var t=a(e,$.vec2());u&&$.distVec2(h,t)>20&&(A(),i())};o.addEventListener("mousemove",p);var f=e.cameraControl.on("rayMove",(function(e){var t=e.canvasPos;r(t,l(t))})),v=function(e){if(1===e.which&&u){c();var t=a(e,$.vec2());s(t,l(t))}};return o.addEventListener("mouseup",v),c}},_I=function(e,t,i){return function(r,s,n){var o,a=e.scene,l=a.canvas.canvas,u=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(l.ownerDocument.body,l,t),t},c=function(e){var t=$.vec3(),r=$.vec3();return $.canvasPosToWorldRay(l,a.camera.viewMatrix,a.camera.projMatrix,e,t,r),i(t,r)},h=null,d=function(){},p=d,f=function(){t.stop(),clearTimeout(h),e.cameraControl.active=!0,p=d,o=null},v=function(){f(),l.removeEventListener("touchstart",g),l.removeEventListener("touchmove",m),l.removeEventListener("touchend",_)},g=function(i){var n=i.touches;if(1!==n.length)f(),r();else{var a=n[0],l=u(a,$.vec2());c(l)&&(o=a.identifier,p=function(e){$.distVec2(l,e)>20&&f()},h=setTimeout((function(){t.start(l),h=setTimeout((function(){t.stop(),e.cameraControl.active=!1,p=function(e){s(e,c(e))},p(l)}),300)}),250))}};l.addEventListener("touchstart",g,{passive:!0});var m=function(e){var t=A(e.changedTouches).find((function(e){return e.identifier===o}));t&&p(u(t,$.vec2()))};l.addEventListener("touchmove",m,{passive:!0});var _=function(e){var t=A(e.changedTouches).find((function(e){return e.identifier===o}));if(t){v();var i=u(t,$.vec2());n(i,c(i))}};return l.addEventListener("touchend",_,{passive:!0}),v}},yI=function(e,t,i,r){var s=-($.dotVec3(i,t)-e)/$.dotVec3(r,t),n=$.vec3();return $.mulVec3Scalar(r,s,n),$.addVec3(i,n,n),n},bI=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(x(this,i),(r=t.call(this,e.viewer.scene,s)).plugin=e,r._container=s.container,!r._container)throw"config missing: container";return r._eventSubs={},r.plugin.viewer.scene,r._geometry=s.geometry,s.onMouseOver,s.onMouseLeave,s.onContextMenu,r._alpha="alpha"in s&&void 0!==s.alpha?s.alpha:.5,r.color=s.color,r._visible=!0,r._rebuildMesh(),r}return C(i,[{key:"_rebuildMesh",value:function(){var e,t=this.plugin.viewer.scene,i=this._geometry.planeCoordinates.slice(),r=this._geometry.height<0,s=this._geometry.altitude+(r?this._geometry.height:0),n=this._geometry.height*(r?-1:1),o=h(dI(i),2),a=o[0],l=o[1],u=[],d=[],p=function(e){var t,i=u.length,r=c(a);try{for(r.s();!(t=r.n()).done;){var o=t.value;u.push([o[0],s+(e?n:0),o[1]])}}catch(e){r.e(e)}finally{r.f()}var h,p=c(l);try{for(p.s();!(h=p.n()).done;){var f=h.value;d.push.apply(d,A((e?f:f.slice(0).reverse()).map((function(e){return e+i}))))}}catch(e){p.e(e)}finally{p.f()}};p(!1),p(!0);for(var f=function(e){var t=a[e],i=a[(e+1)%a.length],r=s,o=s+n,l=u.length;u.push([t[0],r,t[1]],[i[0],r,i[1]],[i[0],o,i[1]],[t[0],o,t[1]]),d.push.apply(d,A([0,1,2,0,2,3].map((function(e){return e+l}))))},v=0;vb?1:0;w|=C,B.push(C)}switch(w){case 0:case 1:m.push(y);break;case 2:break;case 3:for(var M=[],E=0;E=3&&m.push(M)}}}catch(e){_.e(e)}finally{_.f()}i=m}}catch(e){d.e(e)}finally{d.f()}if(0===i.length)return null;var U,O=$.vec3([0,0,0]),N=new Set,Q=c(i);try{for(Q.s();!(U=Q.n()).done;){var V,H=c(U.value);try{for(H.s();!(V=H.n()).done;){var j=V.value,G=j.map((function(e){return e.toFixed(3)})).join(":");N.has(G)||(N.add(G),$.addVec3(O,j,O))}}catch(e){H.e(e)}finally{H.f()}}}catch(e){Q.e(e)}finally{Q.f()}return $.mulVec3Scalar(O,1/N.size,O),O}},{key:"center",get:function(){return this._center}},{key:"altitude",get:function(){return this._geometry.altitude},set:function(e){this._geometry.altitude=e,this._rebuildMesh()}},{key:"height",get:function(){return this._geometry.height},set:function(e){this._geometry.height=e,this._rebuildMesh()}},{key:"highlighted",get:function(){return this._highlighted},set:function(e){this._highlighted=e,this._zoneMesh&&(this._zoneMesh.highlighted=e)}},{key:"color",get:function(){return this._color},set:function(e){this._color=e,this._zoneMesh&&(this._zoneMesh.material.diffuse=cI(this._color))}},{key:"alpha",get:function(){return this._alpha},set:function(e){this._alpha=e,this._zoneMesh&&(this._zoneMesh.material.alpha=this._alpha)}},{key:"edges",get:function(){return this._edges},set:function(e){this._edges=e,this._zoneMesh&&(this._zoneMesh.edges=this._edges)}},{key:"visible",get:function(){return this._visible},set:function(e){this._visible=!!e,this._zoneMesh.visible=this._visible,this._needUpdate()}},{key:"getJSON",value:function(){return{id:this.id,geometry:this._geometry,alpha:this._alpha,color:this._color}}},{key:"duplicate",value:function(){return this.plugin.createZone({id:$.createUUID(),geometry:{planeCoordinates:this._geometry.planeCoordinates.map((function(e){return e.slice()})),altitude:this._geometry.altitude,height:this._geometry.height},alpha:this._alpha,color:this._color})}},{key:"destroy",value:function(){this._zoneMesh.destroy(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),wI=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r._deactivate=null,r}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,r){if(!this._deactivate){if("object"===B(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=mI(a,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function s(){u._deactivate=gI(l,e,t,i,r,u.pointerLens,o,A,(function(e){var t=!0;u._deactivate=function(){t=!1},u.fire("zoneEnd",e),t&&s()})).deactivate}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),BI=function(e){g(i,Se);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,"Zones",e))._pointerLens=s.pointerLens,r._container=s.container||document.body,r._zones=[],r.defaultColor=void 0!==s.defaultColor?s.defaultColor:"#00BBFF",r.zIndex=s.zIndex||1e4,r._onMouseOver=function(e,t){r.fire("mouseOver",{plugin:b(r),zone:t,event:e})},r._onMouseLeave=function(e,t){r.fire("mouseLeave",{plugin:b(r),zone:t,event:e})},r._onContextMenu=function(e,t){r.fire("contextMenu",{plugin:b(r),zone:t,event:e})},r}return C(i,[{key:"createZone",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.viewer.scene.components[t.id]&&(this.error("Viewer scene component with this ID already exists: "+t.id),delete t.id);var i=new bI(this,{id:t.id,plugin:this,container:this._container,geometry:t.geometry,alpha:t.alpha,color:t.color,onMouseOver:this._onMouseOver,onMouseLeave:this._onMouseLeave,onContextMenu:this._onContextMenu});return this._zones.push(i),i.on("destroyed",(function(){var t=e._zones.indexOf(i);t>=0&&e._zones.splice(t,1)})),this.fire("zoneCreated",i),i}},{key:"zones",get:function(){return this._zones}},{key:"destroy",value:function(){f(w(i.prototype),"destroy",this).call(this)}}]),i}(),xI=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r.pointerCircle=new De(e.viewer),r._deactivate=null,r}return C(i,[{key:"active",get:function(){return!!this._deactivate}},{key:"activate",value:function(e,t,i,r){if("object"===B(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._deactivate){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=_I(a,this.pointerCircle,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function s(){u._deactivate=gI(l,e,t,i,r,u.pointerLens,o,A,(function(e){var t=!0;u._deactivate=function(){t=!1},u.fire("zoneEnd",e),t&&s()})).deactivate}()}}},{key:"deactivate",value:function(){this._deactivate&&(this._deactivate(),this._deactivate=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),PI=function(e,t,i,r,s,n,o,a,l){var u,A=n?function(e){n.visible=!!e,e&&(n.canvasPos=e)}:function(){},c=[function(){return A(null)}],h=vI(e,r,s);return c.push((function(){return h.destroy()})),function n(d){var p=fI(e,r),f=d.length>0&&function(e,t,i){var r=e.canvas.canvas,s=new et(e,{});s.worldPos=i;var n=new et(e,{}),o=r.ownerDocument.body,a=new it(o,{color:t,thickness:1,thicknessClickable:6});a.setVisible(!1);var l=function(){var e=s.canvasPos.slice(),t=n.canvasPos.slice();hI(r,o,e),hI(r,o,t),a.setStartAndEnd(e[0],e[1],t[0],t[1])},u=e.camera.on("viewMatrix",l),A=e.camera.on("projMatrix",l);return{update:function(e){e&&(n.worldPos=e,l()),a.setVisible(!!e)},destroy:function(){e.camera.off(u),e.camera.off(A),s.destroy(),n.destroy(),a.destroy()}}}(e,r,d[d.length-1].getWorldPos());c.push((function(){p.destroy(),f&&f.destroy()}));var v=d.length>0&&d[0],g=function(e){var t=v&&v.getCanvasPos();return t&&$.distVec2(t,e)<10&&{canvasPos:t,worldPos:v.getWorldPos()}},m=function(){var e=function(e,t,i){return t[0]<=Math.max(e[0],i[0])&&t[0]>=Math.min(e[0],i[0])&&t[1]<=Math.max(e[1],i[1])&&t[1]>=Math.min(e[1],i[1])},t=function(e,t,i){var r=(t[1]-e[1])*(i[0]-t[0])-(t[0]-e[0])*(i[1]-t[1]);return 0===r?0:r>0?1:2};return function(i,r){for(var s=i[i.length-2],n=i[i.length-1],o=r?1:0;o2?d.map((function(e){return e.getWorldPos()})):null)}),(function(e,t){var i=d.length>2&&g(e);if(v&&v.setHighlighted(!!i),A(i?i.canvasPos:e),p.update(!i&&t),f&&f.update(i?i.worldPos:t),d.length>=2){var r=d.map((function(e){return e.getWorldPos()})).concat(i?[]:[t]),s=m(r.map((function(e){return[e[0],e[2]]})),i);h.updateBase(s?null:r)}else h.updateBase(null)}),(function(e,a){var u=d.length>2&&g(e),A=d.map((function(e){return e.getWorldPos()})).concat(u?[]:[a]);h.updateBase(A);var v=A.map((function(e){return[e[0],e[2]]}));d.length>2&&m(v,u)?(c.pop()(),n(d)):u?(p.update(a),c.forEach((function(e){return e()})),l(o.createZone({id:$.createUUID(),geometry:{planeCoordinates:v,altitude:t,height:i},alpha:s,color:r}))):(p.update(a),f&&f.update(a),n(d.concat(p)))}))}([]),{closeSurface:function(){throw"TODO"},deactivate:function(){u(),c.forEach((function(e){return e()}))}}},CI=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===B(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=mI(a,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function s(){u._action=PI(l,e,t,i,r,u.pointerLens,o,A,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),MI=function(e){g(i,we);var t=_(i);function i(e){var r,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return x(this,i),(r=t.call(this,e.viewer.scene)).zonesPlugin=e,r.pointerLens=s.pointerLens,r.pointerCircle=new De(e.viewer),r._action=null,r}return C(i,[{key:"active",get:function(){return!!this._action}},{key:"activate",value:function(e,t,i,r){if("object"===B(e)&&null!==e){var s=e,n=function(e,t){if(e in s)return s[e];if(void 0!==t)return t;throw"config missing: "+e};e=n("altitude"),t=n("height"),i=n("color","#008000"),r=n("alpha",.5)}if(!this._action){var o=this.zonesPlugin,a=o.viewer,l=a.scene,u=this,A=_I(a,this.pointerCircle,(function(t,i){return yI(e,$.vec3([0,1,0]),t,i)}));!function s(){u._action=PI(l,e,t,i,r,u.pointerLens,o,A,(function(e){var t=!0;u._action={deactivate:function(){t=!1}},u.fire("zoneEnd",e),t&&s()}))}()}}},{key:"deactivate",value:function(){this._action&&(this._action.deactivate(),this._action=null)}},{key:"destroy",value:function(){this.deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),EI=function(e){g(i,we);var t=_(i);function i(e,r,s,n){var o;x(this,i);var a=b(o=t.call(this,e.plugin.viewer.scene)),l=e._geometry.altitude,u=r&&r.pointerLens,A=u?function(e){u.visible=!!e,e&&(u.canvasPos=e)}:function(){},c=e._geometry.planeCoordinates.map((function(t){var i,r,o=function(i){t[0]=i[0],t[1]=i[1];try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}},u=pI(s,n,e.plugin.viewer,$.vec3([t[0],l,t[1]]),e._color,(function(e,t){return yI(l,$.vec3([0,1,0]),e,t)}),(function(){i=u.getWorldPos().slice(),r=t.slice(),h(!1,u)}),(function(e,t){A(e),o([t[0],t[2]])}),(function(){e._zoneMesh?a.fire("edited"):(u.setWorldPos(i),o(r)),A(null),h(!0,u)}));return u})),h=function(e,t){return c.forEach((function(i){return i!==t&&i.setActive(e)}))};h(!0);var d=function(){c.forEach((function(e){return e.destroy()})),A(null)},p=e.on("destroyed",d);return o._deactivate=function(){e.off("destroyed",p),d()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),FI=function(e){g(i,EI);var t=_(i);function i(e,r){return x(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),kI=function(e){g(i,EI);var t=_(i);function i(e,r){return x(this,i),t.call(this,e,r,!1,!0)}return C(i)}(),II=function(e){g(i,we);var t=_(i);function i(e,r,s,n){var o;x(this,i);var a=e.plugin.viewer,l=a.scene,u=l.canvas.canvas,c=b(o=t.call(this,l)),h=e._geometry.altitude,d=r&&r.pointerLens,p=d?function(e){d.visible=!!e,e&&(d.canvasPos=e)}:function(){},f=function(e){var t,i,r=$.vec3(),s=$.vec3();return $.canvasPosToWorldRay(u,l.camera.viewMatrix,l.camera.projMatrix,e,r,s),t=r,i=s,yI(h,$.vec3([0,1,0]),t,i)},v=function(e,t){return t[0]=e.clientX,t[1]=e.clientY,hI(u.ownerDocument.body,u,t),t},g=function(e,t){var i=function(e){e.preventDefault(),t(e)};return u.addEventListener(e,i),function(){return u.removeEventListener(e,i)}},m=function(){},_=function(t,i,r,s){var n,o,l,A,h=s(t),d=v(h,$.vec2()),_=a.scene.pick({canvasPos:d,includeEntities:[e._zoneMesh.id]});if((_&&_.entity&&_.entity.zone)===e){m(),u.style.cursor="move",a.cameraControl.active=!1;var y=(n=e._geometry.planeCoordinates.map((function(e){return e.slice()})),o=f(d),l=$.vec2([o[0],o[2]]),A=$.vec2(),function(t){var i=f(t);A[0]=i[0],A[1]=i[2],$.subVec2(l,A,A),e._geometry.planeCoordinates.forEach((function(e,t){$.subVec2(n[t],A,e)}));try{e._rebuildMesh()}catch(t){e._zoneMesh&&(e._zoneMesh.destroy(),e._zoneMesh=null)}}),b=g(i,(function(e){var t=s(e);if(t){var i=v(t,$.vec2());y(i),p(i)}})),w=g(r,(function(e){var t=s(e);if(t){var i=v(t,$.vec2());y(i),p(null),m(),c.fire("translated")}}));m=function(){m=function(){},u.style.cursor="default",a.cameraControl.active=!0,b(),w()}}},y=[];s&&y.push(g("mousedown",(function(e){1===e.which&&_(e,"mousemove","mouseup",(function(e){return 1===e.which&&e}))}))),n&&y.push(g("touchstart",(function(e){if(1===e.touches.length){var t=e.touches[0].identifier;_(e,"touchmove","touchend",(function(e){return A(e.changedTouches).find((function(e){return e.identifier===t}))}))}})));var w=function(){m(),y.forEach((function(e){return e()})),p(null)},B=e.on("destroyed",w);return o._deactivate=function(){e.off("destroyed",B),w()},o}return C(i,[{key:"deactivate",value:function(){this._deactivate(),f(w(i.prototype),"destroy",this).call(this)}}]),i}(),DI=function(e){g(i,II);var t=_(i);function i(e,r){return x(this,i),t.call(this,e,r,!0,!1)}return C(i)}(),SI=function(e){g(i,II);var t=_(i);function i(e,r){return x(this,i),t.call(this,e,r,!1,!0)}return C(i)}();export{xr as AlphaFormat,wi as AmbientLight,lt as AngleMeasurementsControl,ut as AngleMeasurementsMouseControl,At as AngleMeasurementsPlugin,ct as AngleMeasurementsTouchControl,vt as AnnotationsPlugin,cn as AxisGizmoPlugin,_h as BCFViewpointsPlugin,$n as Bitmap,pr as ByteType,od as CameraMemento,Qh as CameraPath,Kh as CameraPathAnimation,lI as CityJSONLoaderPlugin,tr as ClampToEdgeWrapping,we as Component,ds as CompressedMediaType,Yo as Configs,z as ContextMenu,cd as CubicBezierCurve,Uh as Curve,kc as DefaultLoadingManager,Fr as DepthFormat,kr as DepthStencilFormat,bi as DirLight,Eh as DistanceMeasurementsControl,Fh as DistanceMeasurementsMouseControl,kh as DistanceMeasurementsPlugin,Ih as DistanceMeasurementsTouchControl,uI as DotBIMDefaultDataSource,AI as DotBIMLoaderPlugin,ji as EdgeMaterial,Vi as EmphasisMaterial,KE as FaceAlignedSectionPlanesPlugin,Dh as FastNavPlugin,_r as FloatType,Nn as Fresnel,Me as Frustum,Ce as FrustumPlane,As as GIFMediaType,Sh as GLTFDefaultDataSource,cE as GLTFLoaderPlugin,yr as HalfFloatType,qh as ImagePlane,gr as IntType,cs as JPEGMediaType,Rc as KTX2TextureTranscoder,Fk as LASLoaderPlugin,Bn as LambertMaterial,sd as LightMap,ph as LineSet,ls as LinearEncoding,lr as LinearFilter,hr as LinearMipMapLinearFilter,Ar as LinearMipMapNearestFilter,cr as LinearMipmapLinearFilter,ur as LinearMipmapNearestFilter,Ic as Loader,Fc as LoadingManager,Th as LocaleService,Er as LuminanceAlphaFormat,Mr as LuminanceFormat,Q as Map,et as Marker,ke as MarqueePicker,Ie as MarqueePickerMouseControl,nn as Mesh,Cn as MetallicMaterial,ir as MirroredRepeatWrapping,ld as ModelMemento,fE as NavCubePlugin,rr as NearestFilter,ar as NearestMipMapLinearFilter,sr as NearestMipMapNearestFilter,or as NearestMipmapLinearFilter,nr as NearestMipmapNearestFilter,wn as Node,PE as OBJLoaderPlugin,te as ObjectsKdTree3,Ad as ObjectsMemento,hs as PNGMediaType,hd as Path,pd as PerformanceModel,Ni as PhongMaterial,xt as PickResult,Se as Plugin,$h as PointLight,De as PointerCircle,W as PointerLens,dd as QuadraticBezierCurve,ie as Queue,Cr as RGBAFormat,Lr as RGBAIntegerFormat,ss as RGBA_ASTC_10x10_Format,ts as RGBA_ASTC_10x5_Format,is as RGBA_ASTC_10x6_Format,rs as RGBA_ASTC_10x8_Format,ns as RGBA_ASTC_12x10_Format,os as RGBA_ASTC_12x12_Format,Kr as RGBA_ASTC_4x4_Format,Xr as RGBA_ASTC_5x4_Format,Yr as RGBA_ASTC_5x5_Format,Jr as RGBA_ASTC_6x5_Format,Zr as RGBA_ASTC_6x6_Format,qr as RGBA_ASTC_8x5_Format,$r as RGBA_ASTC_8x6_Format,es as RGBA_ASTC_8x8_Format,as as RGBA_BPTC_Format,Wr as RGBA_ETC2_EAC_Format,jr as RGBA_PVRTC_2BPPV1_Format,Hr as RGBA_PVRTC_4BPPV1_Format,Ur as RGBA_S3TC_DXT1_Format,Or as RGBA_S3TC_DXT3_Format,Nr as RGBA_S3TC_DXT5_Format,Pr as RGBFormat,Gr as RGB_ETC1_Format,zr as RGB_ETC2_Format,Vr as RGB_PVRTC_2BPPV1_Format,Qr as RGB_PVRTC_4BPPV1_Format,Rr as RGB_S3TC_DXT1_Format,Sr as RGFormat,Tr as RGIntegerFormat,Ti as ReadableGeometry,Ir as RedFormat,Dr as RedIntegerFormat,rd as ReflectionMap,er as RepeatWrapping,YE as STLDefaultDataSource,sF as STLLoaderPlugin,hh as SceneModel,ro as SceneModelMesh,rh as SceneModelTransform,hn as SectionPlane,SE as SectionPlanesPlugin,fr as ShortType,fd as Skybox,XE as SkyboxesPlugin,Fn as SpecularMaterial,Oh as SplineCurve,nd as SpriteMarker,NE as StoreyViewsPlugin,On as Texture,vd as TextureTranscoder,aF as TreeViewPlugin,dr as UnsignedByteType,Br as UnsignedInt248Type,mr as UnsignedIntType,br as UnsignedShort4444Type,wr as UnsignedShort5551Type,vr as UnsignedShortType,Hn as VBOGeometry,hF as ViewCullPlugin,nb as Viewer,bk as WebIFCLoaderPlugin,Tc as WorkerPool,dF as XKTDefaultDataSource,rk as XKTLoaderPlugin,_k as XML3DLoaderPlugin,EI as ZoneEditControl,FI as ZoneEditMouseControl,kI as ZoneEditTouchControl,II as ZoneTranslateControl,DI as ZoneTranslateMouseControl,SI as ZoneTranslateTouchControl,wI as ZonesMouseControl,BI as ZonesPlugin,CI as ZonesPolysurfaceMouseControl,MI as ZonesPolysurfaceTouchControl,xI as ZonesTouchControl,Li as buildBoxGeometry,Wn as buildBoxLinesGeometry,Kn as buildBoxLinesGeometryFromAABB,an as buildCylinderGeometry,Xn as buildGridGeometry,Yn as buildPlaneGeometry,Zn as buildPolylineGeometry,qn as buildPolylineGeometryFromCurve,ln as buildSphereGeometry,Jn as buildTorusGeometry,An as buildVectorTextGeometry,Le as createRTCViewMat,Fe as frustumIntersectsAABB3,Oc as getKTX2TextureTranscoder,Ne as getPlaneRTCPos,Gn as load3DSGeometry,zn as loadOBJGeometry,$ as math,Oe as rtcToWorldPos,us as sRGBEncoding,Ee as setFrustum,re as stats,le as utils,Re as worldToRTCPos,Ue as worldToRTCPositions};